Mi predispongo una tabella di database in cui vi siano i tre campi.
class Helper extends SQLiteOpenHelper{
public Helper(Context context) {
super(context, "database", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE TABELLA(_ID INTEGER PRIMARY KEY,ETICHETTA TEXT,CATEGORIA TEXT,IMMAGINE BLOB)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Ora creo il metodo save e il metodo query.Ma prima forse mi conviene definire una classe che abbia tutte le proprietà
E qui la cosa si fa interessante per la gestione dell'immagine.
Credo che mi convenga memorizzare un array di bytes.
class JImage{
public String Etichetta;
public String Categoria;
public byte[] ImageByteArray;
}
Questo presuppone che nell'immissione di dati venga creata prima la ByteArrayOutputStream e quindi dalla bitmap venga fatta la compressione con successiva conversione della ByteArrayOutputStream in byte di array.Adesso provo a creare il metodo save().
public void save(JImage jImage){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("ETICHETTA", jImage.Etichetta);
values.put("CATEGORIA", jImage.Categoria);
values.put("IMMAGINE", jImage.ImageByteArray);
db.insert("TABELLA", null, values);
}
Ecco.Adesso devo costruire il meccanismo per l'immissione dell'immagine e delle sue caratteristiche.
Fatto.
Il codice che ho inserito è questo (completo):
public class Scelta extends Activity {
//DICHIARAZIONI
Bitmap bmp;
JImage jImage;
Helper helper;
Button button;
Adapter adapter;
ImageView imageView;
EditText editText;
AutoCompleteTextView autoComplete;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scelta);
//DEFINIZIONI
helper=new Helper(this);
imageView=(ImageView) findViewById(R.id.imageView1);
editText=(EditText) findViewById(R.id.editText1);
autoComplete=(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
button=(Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setData(Uri.parse("content://media/external/images/media"));
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent,0);
}
});
adapter=new Adapter(this,helper.catQuery(" "));
autoComplete.setAdapter(adapter);
autoComplete.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 50, stream);
byte[] blob=stream.toByteArray();
jImage=new JImage();
jImage.Etichetta=editText.getText().toString();
jImage.Categoria=autoComplete.getText().toString();
jImage.ImageByteArray=blob;
helper.save(jImage);
jImage=null;
bmp=null;
return false;
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(resultCode==RESULT_OK){
BitmapFactory.Options opzioni=new BitmapFactory.Options();
opzioni.inJustDecodeBounds=true;
BitmapFactory.decodeFile(getPathFromUri(data.getData()),opzioni);
int fattore=1;
while(opzioni.outWidth/fattore>200 && opzioni.outHeight/fattore>200){
fattore*=2;
}
opzioni.inSampleSize=fattore;
opzioni.inJustDecodeBounds=false;
bmp=BitmapFactory.decodeFile(getPathFromUri(data.getData()),opzioni);
imageView.setImageBitmap(bmp);
}
}
private String getPathFromUri(Uri uri){
Cursor crs=getContentResolver().query(uri, null, null, null, null);
crs.moveToFirst();
int index=crs.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
String s=crs.getString(index);
return s;
}
class Helper extends SQLiteOpenHelper{
public Helper(Context context) {
super(context, "database", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE TABELLA(_id INTEGER PRIMARY KEY,ETICHETTA TEXT,CATEGORIA TEXT,IMMAGINE BLOB)");
db.execSQL("CREATE TABLE TBLCATEGORIE(_id INTEGER PRIMARY KEY,CATEGORIA TEXT)");
}
public void save(JImage jImage){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("ETICHETTA", jImage.Etichetta);
values.put("CATEGORIA", jImage.Categoria);
values.put("IMMAGINE", jImage.ImageByteArray);
db.insert("TABELLA", null, values);
values.clear();
values.put("CATEGORIA", jImage.Categoria);
db.insert("TBLCATEGORIE", null, values);
imageView.setImageBitmap(null);
editText.setText(null);
autoComplete.setText(null);
}
public Cursor query(){
SQLiteDatabase db=this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM TABELLA", null);
c.moveToFirst();
return c;
}
public Cursor catQuery(String str){
SQLiteDatabase db=this.getWritableDatabase();
Cursor c=db.rawQuery("SELECT * FROM TBLCATEGORIE WHERE CATEGORIA LIKE '"+str+"%'", null);
c.moveToFirst();
return c;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
class JImage{
public String Etichetta;
public String Categoria;
public byte[] ImageByteArray;
}
class Adapter extends CursorAdapter{
public Adapter(Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
TextView v=(TextView) inflater.inflate(android.R.layout.simple_dropdown_item_1line, null);
return v;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
((TextView)view).setText(cursor.getString(1));
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint){
if(constraint!=null) return helper.catQuery(constraint+"");
return null;
}
@Override
public String convertToString(Cursor cursor){
return cursor.getString(1);
}
}
Questo codice è stato trasferito su un'altra activity, chiamata "Scelta".
Ora vorrei visualizzare le immagini su dei LinearLayout.
Per prima cosa, trasferisco il codice su un'altra activity.
E l'ho fatto, ripassando l'Intent esplicito (per passare da un'activity all'altra.
button=(Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,Scelta.class);
startActivity(intent);
}
});
Bene.Ora, all'avvio di questa Activity, voglio che le immagini salvate nel database vengano riportate su dei LinearLayout.
Devo ripassare le procedure per creare programmaticamente un linearlayout.
LinearLayout ll = new LinearLayout(this);E poi?
Ecco il codice per aggiungere un Layout all'Activity:
LinearLayout ll = new LinearLayout(this); ll.setBackgroundColor(Color.BLUE); ll.setOrientation(LinearLayout.VERTICAL); AbsoluteLayout.LayoutParams params=new AbsoluteLayout.LayoutParams(200,200,100,0); ll.setLayoutParams(params); AbsoluteLayout abs=(AbsoluteLayout)findViewById(R.id.lay); abs.addView(ll);Ora potrebbe essere utile disegnare un bordo al layout.
Questa è una novità.
E ho trovato subito la soluzione
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
AbsoluteLayout.LayoutParams params=new AbsoluteLayout.LayoutParams(200,200,100,0);
ll.setLayoutParams(params);
GradientDrawable gd=new GradientDrawable();
gd.setColor(Color.WHITE);
gd.setStroke(5, Color.BLACK);
ll.setBackground(gd);
AbsoluteLayout abs=(AbsoluteLayout)findViewById(R.id.lay);
abs.addView(ll);
...che mi dà un Layout bianco con un bordo nero di spessore 5 (il numero che appare come parametro nel metodo setStroke).
Nessun commento:
Posta un commento