Image of an ImageView to int Android Studio - java

Good friends, how can I pass the image of an ImageView to int in andrid studio to be able to save it in a BD, I load the image from a database in this way:
Intent intent = getIntent ();
Bundle b = intent.getExtras ();
AdminSQLiteOpenHelper adminPlants = new AdminSQLiteOpenHelper (this, "Plants", null, 1);
SQLiteDatabasePlantsDatabase = PlantsPlants.getWritableDatabase ();
Cursor file_plants = BaseDeDatosPlantas.rawQuery
("SELECT * from species where commonname = '" + b.getString ("name") + "'", null);
if (file_plantas.moveToFirst ()) {
tvNameE.setText (b.getString ("name"));
tvSpeciesE.setText (file_plants.getString (2));
tvDescripcionE.setText (file_plantas.getString (4));
imgFotoE.setImageResource (file_plantas.getInt (5)); // Here I send the image to the ImageView
}
PlantsDatabase.close ();
In the app, the image is changed for another on the device, now as I do the opposite, get the image from the ImageView and pass it to an int and thus be able to save it in BD again.
public void SaveE (View view) {
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper (this, "Plants", null, 1);
SQLiteDatabase DataBase = admin.getWritableDatabase ();
Database.execSQL ("update species set description = '" + tvDescripcionE.getText () + "', photo =" + imageResource
+ "where CommonName = '" + tvNameE.getText () + "';"); // This is where I need the int of the image
Database.close ();
}

As ImageView can host any type of Drawable, not just one specified by a resource id, there's no API to get the resource id back out of the ImageView.
That said, you could always save the resource id to the ImageView as a tag when you assign it:
int resourceId = file_plantas.getInt (5);
imgFotoE.setImageResource (resourceId);
imgFotoE.setTag(resourceId);
And then you could retrieve it later:
int resourceId = (int) imgFotoE.getTag();

Related

How to create a List from data in a SQL database using java?

I am struggling to find an anwser to this question : how do I create a List with data from a SQL database in Java ? (I am using Android Studio)
I need to create :
lists for dropdown menus and autoCompleteTextView. For these, I need all the values of a specific column, not the whole line ("what are the different brands that exist in my table ?")
lists for all objects sharing the same attribute ("which objects have the same brand ?")
Here is my constructor for the database :
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"favori TEXT, " +
"type TEXT, " +
"marque TEXT, " +
"nom TEXT, " +
"nomGenerique TEXT, " +
"image BLOB, " +
"prix TEXT, " +
"codeBarres TEXT, " +
"quantite TEXT, " +
"quantiteRestante TEXT, " +
"notes TEXT)");
}
And this is my data model (in a Modele.class) - I have all the getters and setters after this - :
public InventaireAlcool(int id, Boolean favori, String type, String marque,
String nom, String nomGenerique, byte[] image, int prix,
int codeBarres, int quantite, int quantiteRestante, String notes) {
this.id = id;
this.favori = favori;
this.type = type;
this.marque = marque;
this.nom = nom;
this.nomGenerique = nomGenerique;
this.image = image;
this.prix = prix;
this.codeBarres = codeBarres;
this.quantite = quantite;
this.quantiteRestante = quantiteRestante;
this.notes = notes;
}
I have an activity (AjoutReference) where I fill a form and when I click on the save button, this is what it does :
Boolean get_favori = favori.isChecked();
String get_type = autoCompleteType.getText().toString();
String get_marque = autoCompleteMarque.getText().toString();
String get_nom = editTextNom.getText().toString();
String get_nomGenerique = editTextNomGenerique.getText().toString();
String get_prix = editTextPrix.getText().toString();
String get_code = editTextCode.getText().toString();
String get_quantite = quantite.getText().toString();
String get_quantiteRestante = String.valueOf(sliderQuantite.getValue());
String get_notes = editTextNotes.getText().toString();
boolean res = inventaireDb.ajoutInventaire(get_favori, get_type, get_marque,
get_nom, get_nomGenerique, ImageToByte(imageView), get_prix, get_code, get_quantite, get_quantiteRestante, get_notes);
if (res == true){
Toast.makeText(AjoutReference.this, "Reference added", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AjoutReference.this, MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(AjoutReference.this, "Error", Toast.LENGTH_SHORT).show();
}
The data from the database is then displayed on a RecyclerView with this code (in a RecyclerViewAdapter class):
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.nomGenerique.setText(inventaireAlcoolList.get(position).getNomGenerique());
holder.marque.setText(inventaireAlcoolList.get(position).getMarque());
holder.type.setText(inventaireAlcoolList.get(position).getType());
Glide.with(this.context).load(inventaireAlcoolList.get(position).getImage()).into(holder.image);
holder.quantite.setText(String.valueOf(inventaireAlcoolList.get(position).getQuantite()));
I could not find any specific documentation or answer clear enough to help :-(
Any advice would be very much welcome!
And if you wonder what I will use this app for : it is to handle my alcohol stock. I currently have an excel table with more than 120 lines and it is a pain to maintain and keep updated (and, no, I'm not a bartender, just a whisky, gin and rhum enthusiast).
The app should allow me to know how many bottles I have, in which condition ("remaining quantity" is a slider that lets me specify how much is left in a bottle and, when I'm out shopping, I can make sure I buy a refill :-) ), the lowest price I got, to create a "favorites" list...
Edit :
I found the solution thanks to the link provided by Int'l Man of Coding Mystery.
I created methods inside my database class to provide me with lists of column contents. Here is the code, hoping it might help someone else.
public ArrayList getTypeExtract(){
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> arrayList = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT type FROM " + TABLE_NAME, null);
while (cursor.moveToNext()){
String typeExtract = cursor.getString(0);
arrayList.add(typeExtract);
}
return arrayList;
}
I also learned that :
"SELECT type FROM " returns the type column from the database. I can add other columns just by adding their name : "SELECT type, marque FROM " for instance.
cursor.getString(0) the 0 is the column index for the extraction. I have only one column in my example so it has to be 0 (and not column 2, the column index inside the database)...
Thanks for the help!

Unable to load images by image path stored in mysql using javafx

Below here is my example code.
It loads images saved in a local folder by using the remaining image relative path stored in mysql, but it said unknown source..please help..
public void LoadTimelineImg() throws SQLException {
String sql = "select id, img_url from t_timeline order by id";
Statement selecStatement = conn.createStatement();
ResultSet resultSet = selecStatement.executeQuery(sql);
while(resultSet.next()) {
int id = resultSet.getInt("id");
ArrayList<Image> images = new ArrayList<Image>();
String img_path = resultSet.getString("img_url");
images.add(new Image("\"" + "/application/images/" + img_path + "\""));
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(5), event -> {
imageView.setImage(images.get(count));
count++;
if(count == 5){
count = 0;
}
}));
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
}
}
The Image class constructor take a string as parameter. This string musn't be double quoted like the one you're providing.
So you can do the following:
String rootPath = "/application/images/"; // or "C:/application/images/" on windows
// assuming img_path = "somefolder1/somefolder2/imagename.ext"
Image img = new Image(rootPath + img_path);
or
String rootPath = "/application/images/"; // or "C:/application/images/" on windows
// assuming img_path = "somefolder1/somefolder2/imagename.ext"
File file = new File(rootPath, img_path);
Image img = new Image(file.toURI().toURL().toString());

How to find and prefix all phone number in Contacts Android?

Sorry for the bad english!
I want to scan all contacts 's phone number and prefix them. However my code is not useful. It missed a lot of phone numbers when reading contacts. Help me plz!
`
String[] columns = {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER};
ContentResolver cr =getContentResolver();
Cursor cursor=cr.query(ContactsContract.Contacts.CONTENT_URI, columns,null,null,null);
cursor.moveToFirst();
while(cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if(!(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)).endsWith("0")) )
{
Cursor phones = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
if(phones.getCount() > 0)
while (phones.moveToNext())
{
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("[ \\-().]", ""); //this is phone number
int type = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String idIndex = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
switch (type)
{
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
//prefix number function and write contacts here.
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
//prefix number function and write contacts here.
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
//prefix number function and write contacts here.
break;
//some other type here...
}
}
phones.close();
}
}
cursor.close();`
No need for a loop-within-loop here, just one query that goes over all numbers in the Contacts DB:
String[] projection = new String[] { Phone.NUMBER, Phone.TYPE, Phone._ID };
Cursor phones = cr.query(Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String number = phones.getString(0).replaceAll("[ \\-().]", ""); //you can instead use Phone.NORMALIZED_NUMBER if you're using a high-enough API level
int type = phones.getInt(1);
long id = cursor.getLong(2);
Log.v("LOG", "got phone: " + id + ", " + number + ", " + type);
prefixNumber(id, number, type);
}
phones.close();
`sssss
public void updatePhoneNumber(ContentResolver contentResolver, long rawContactId, int phoneType, String PhoneNumber) {
// Create content values object.
ContentValues contentValues = new ContentValues();
// Put new phone number value.
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, PhoneNumber);
// Create query condition, query with the raw contact id.
StringBuffer whereClauseBuf = new StringBuffer();
// Specify the update contact id.
whereClauseBuf.append(ContactsContract.Data.RAW_CONTACT_ID);
whereClauseBuf.append("=");
whereClauseBuf.append(rawContactId);
// Specify the row data mimetype to phone mimetype( vnd.android.cursor.item/phone_v2 )
whereClauseBuf.append(" and ");
whereClauseBuf.append(ContactsContract.Data.MIMETYPE);
whereClauseBuf.append(" = '");
String mimetype = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
whereClauseBuf.append(mimetype);
whereClauseBuf.append("'");
// Specify phone type.
whereClauseBuf.append(" and ");
whereClauseBuf.append(ContactsContract.CommonDataKinds.Phone.TYPE);
whereClauseBuf.append(" = ");
whereClauseBuf.append(phoneType);
// Update phone info through Data uri.Otherwise it may throw java.lang.UnsupportedOperationException.
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Get update data count.
int updateCount = contentResolver.update(dataUri, contentValues, whereClauseBuf.toString(), null);
}`

fastest way to load image thumbnails into grid

I'm trying to show a gridview with all the users images in it.
but loading the images from the android MediaStore.
I have to do a request and then loop over the images from the result to get every single thumbnail, this results in a huge lag!
how would I compress these calls into a single request or how would I save more time on this?
String[] projection = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.TITLE,
MediaStore.Images.Media.DATA,
MediaStore.Images.Media.MIME_TYPE,
MediaStore.Images.Media.SIZE,
MediaStore.Images.Media.DATE_TAKEN,
MediaStore.Images.Media.DATE_ADDED,
MediaStore.Images.Media.DATE_MODIFIED,
MediaStore.Images.Media.ORIENTATION
};
String sortOrder = MediaStore.Images.Media.DATE_ADDED + " DESC, " +
MediaStore.Images.Media.DATE_MODIFIED + " DESC";
ContentResolver cr = ctx.getContentResolver();
final Cursor cursorImages = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
sortOrder);
ArrayList<ImageDataHolder> images = new ArrayList<ImageDataHolder>(cursorImages.getCount());
if (cursorImages.moveToFirst()) {
final int dataColumn = cursorImages.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
final int idColumn = cursorImages.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
do {
final Long imageID = cursorImages.getLong(idColumn);
final String imagePath = cursorImages.getString(dataColumn);
final int imageOrientation = cursorImages.getInt(dataColumn);
// create new cursor to get thumbnail path
final Cursor cursorThumb = MediaStore.Images.Thumbnails.queryMiniThumbnail(ctx.getContentResolver(), imageID,
MediaStore.Images.Thumbnails.MINI_KIND, null);
String thumbPath = "";
if (cursorThumb != null) {
if (cursorThumb.getCount() > 0) {
cursorThumb.moveToFirst();
thumbPath = cursorThumb.getString(cursorThumb.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
}
cursorThumb.close(); // cleanup crew, isle 7
}
// create new ImageDataHolder and add to images ArrayList
// only if we have a thumbnail to show
if (thumbPath != "")
images.add(new ImageDataHolder(imagePath, thumbPath, imageID, imageOrientation));
} while (cursorImages.moveToNext());
}
cursorImages.close();
return images;

Get all data from SQLite trough search

I am trying to get all data from my SQLite using Query LIKE statement. But I don't know how to get it.
I try to modified the Query that I use to get All the data without filtering, and its work fine.
I already try to search this problem but I still don't get it.
Here's my Search.java
Intent search = getIntent();
String searchResult = search.getStringExtra("TAG_SEARCH");
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
Log.d("Reading: ", "Reading all contacts..");
List <AllItem> allItems = new ArrayList<AllItem>();
allItems = db.getAllSearchResult();
ArrayList <String> allItems2 = new ArrayList<String>();
for (AllItem cn : allItems) {
allItems2.add(cn.getItem_name());
allItems2.add(cn.getAreaNAme());
allItems2.add(cn.getPriceCategory());
allItems2.add(cn.getImageCount());
allItems2.add(cn.getID());
allItems2.add(cn.getCategory_name());
allItems2.add(cn.getKids());
allItems2.add(cn.getFreeTextForKids());
allItems2.add(cn.getDescription());
allItems2.add(cn.getPromotion());
allItems2.add(cn.getPromotionFreeText());
allItems2.add(cn.getPromotionStartDate() + " - ");
allItems2.add(cn.getPromotionEndDate());
allItems2.add(cn.getYoutube());
allItems2.add(cn.getYoutubeLink());
allItems2.add(cn.getPhone());
allItems2.add(cn.getMobilePhone());
allItems2.add(cn.getReview());
allItems2.add(cn.getAddress());
allItems2.add(cn.getLatitude());
allItems2.add(cn.getLongitude());
allItems2.add(cn.getOpenDetail());
allItems2.add(cn.getFacebook());
allItems2.add(cn.getTwitter());
allItems2.add(cn.getInstagram());
allItems2.add(cn.getWebsite());
}
CustomAdapterAccommodation adapter = new CustomAdapterAccommodation(Search.this, allItems2);
listview.setAdapter(adapter);
}
I want to use the String from Intent to search the data on DATABASE.
This is my DatabaseHandler.java
// Getting All search result
public List<AllItem> getAllSearchResult() {
List<AllItem> allsearchResultList = new ArrayList<AllItem>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ALLITEM;
// If i try change like this its show nothing
// String selectQuery = "SELECT * FROM " + TABLE_ALLITEM + " WHERE " + KEY_ITEM_NAME_ALLITEM + " = '%a%'";
Log.d("Query search", selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
AllItem allitem = new AllItem();
allitem.setTableID(cursor.getInt(0));
allitem.setID(cursor.getString(1));
allitem.setCategory_name(cursor.getString(2));
allitem.setItem_Name(cursor.getString(3));
allitem.setDescription(cursor.getString(4));
allitem.setAddress(cursor.getString(5));
allitem.setArea (cursor.getString(6));
allitem.setAreaName (cursor.getString(7));
allitem.setLongitude (cursor.getString(8));
allitem.setLatitude (cursor.getString(9));
allitem.setOpenDetail (cursor.getString(10));
allitem.setKids (cursor.getString(11));
allitem.setFreeTextForKids (cursor.getString(12));
allitem.setCuisineID (cursor.getString(13));
allitem.setCuisineName (cursor.getString(14));
allitem.setCuisineUniqueCode (cursor.getString(15));
allitem.setBarTypeID (cursor.getString(16));
allitem.setBarTypeName (cursor.getString(17));
allitem.setBarTypeCode (cursor.getString(18));
allitem.setRoomTypeID (cursor.getString(19));
allitem.setRoomTypeName (cursor.getString(20));
allitem.setRoomTypeCode (cursor.getString(21));
allitem.setWellnessTypeID (cursor.getString(22));
allitem.setWellnessTypeName (cursor.getString(23));
allitem.setWellnessTypeCode (cursor.getString(24));
allitem.setAttractionsTypeID (cursor.getString(25));
allitem.setAttractionsTypeName (cursor.getString(26));
allitem.setAttractionsTypeCode (cursor.getString(27));
allitem.setShopsTypeID (cursor.getString(28));
allitem.setShopsTypeName (cursor.getString(29));
allitem.setShopsTypeCode (cursor.getString(30));
allitem.setAdventuresTypeID (cursor.getString(31));
allitem.setAdventuresTypeName (cursor.getString(32));
allitem.setAdventuresTypeCode (cursor.getString(33));
allitem.setRomanceTypeID (cursor.getString(34));
allitem.setRomanceTypeName (cursor.getString(35));
allitem.setRomanceTypeCode (cursor.getString(36));
allitem.setGalleriesTypeID (cursor.getString(37));
allitem.setGalleriesTypeName (cursor.getString(38));
allitem.setGalleriesTypeCode (cursor.getString(39));
allitem.setFurnitureTypeID (cursor.getString(40));
allitem.setFurnitureTypeName (cursor.getString(41));
allitem.setFurnitureTypeCode (cursor.getString(42));
allitem.setEventTypeID (cursor.getString(43));
allitem.setEventTypeName (cursor.getString(44));
allitem.setEventTypeCode (cursor.getString(45));
allitem.setPriceCategory (cursor.getString(46));
allitem.setHotelOfficialStarRating (cursor.getString(47));
allitem.setPhone (cursor.getString(48));
allitem.setMobilePhone (cursor.getString(49));
allitem.setReview (cursor.getString(50));
allitem.setPromotion (cursor.getString(51));
allitem.setPromotionFreeText (cursor.getString(52));
allitem.setPromotionStartDate (cursor.getString(53));
allitem.setPromotionEndDate (cursor.getString(54));
allitem.setActive (cursor.getString(55));
allitem.setImageCount (cursor.getString(56));
allitem.setCreatedBy (cursor.getString(57));
allitem.setCreatedDate (cursor.getString(58));
allitem.setUpdatedBy (cursor.getString(59));
allitem.setUpdatedDate (cursor.getString(60));
allitem.setFacebook (cursor.getString(61));
allitem.setTwitter (cursor.getString(62));
allitem.setInstagram (cursor.getString(63));
allitem.setWebsite (cursor.getString(64));
allitem.setYoutube (cursor.getString(65));
allitem.setYoutubeLink (cursor.getString(66));
allitem.setMember (cursor.getString(67));
allitem.setMemberStartDate (cursor.getString(68));
allitem.setMemberEndDate (cursor.getString(69));
allitem.setNew (cursor.getString(70));
allitem.setEventStartDate (cursor.getString(71));
allitem.setEventEndDate (cursor.getString(72));
// Adding food to list
allsearchResultList.add(allitem);
} while (cursor.moveToNext());
}
// return food list
return allsearchResultList;
}
Is there anyone can help me how to solved this problem?
When the user press the button search, the Text send to Search class and the Text is the key to get all the data from SQLite. Then show it in ListView.
Thanks before :D
Use LIKE not =
LIKE allows you to use wildcars:
% represents multiple characters
_ represents one character
String filter = "a";
String selectQuery = "SELECT * FROM " + TABLE_ALLITEM + " WHERE " + KEY_ITEM_NAME_ALLITEM + " LIKE '%"+filter+"%' ";

Categories