Get all data from SQLite trough search - java

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+"%' ";

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!

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);
}`

How to sort or reorder MergeCursor for ListViewAdapter

I am developing a simple social media for my case study. I was able to retrieve the post from the people the user follows. Here's the screenshot:
As you can see, the problem is that the posts were not sorted according to date/id. Instead, it is sorted according to the people the user follows. It is because I am only merging the cursors using mergecursor. Here's a part of my code:
ListView listviewFeed = (ListView) findViewById(R.id.listviewFeed);
Cursor cursorFeed = DataAdapters.getFeed(dbHelper, strUserID);
//This code is for retrieving user's own posts
Cursor cursorFollowing = DataAdapters.getFollowing(dbHelper,strUserID);
//This code is for retrieving the followed users.
if(cursorFollowing.getCount()>0) {
for (int intCtr = 0; intCtr < cursorFollowing.getCount(); intCtr++) {
int intUseridI = cursorFollowing.getColumnIndex(Tables.FollowTable.COLUMN_USERID);
String strUseridI = cursorFollowing.getString(intUseridI);
Cursor cursorFollowingFeed = DataAdapters.getFeed(dbHelper, strUseridI);
\\This code is for retrieving the posts of the people the user follows.
if(intCtr>0)
{
mergeCursor = new MergeCursor(new Cursor[]{mergeCursor, cursorFollowingFeed});
}else {
mergeCursor = new MergeCursor(new Cursor[]{cursorFeed, cursorFollowingFeed});
}
//This code is for merging the cursors.
if (intCtr + 1 == cursorFollowing.getCount()) {
cursorFollowing.close();
} else {
cursorFollowing.moveToNext();
}
}
ListViewAdapterMeasurement adapterMeasurement = new ListViewAdapterMeasurement(this, mergeCursor);
listviewFeed.setAdapter(adapterMeasurement);
}else
{
ListViewAdapterMeasurement adapterMeasurement = new ListViewAdapterMeasurement(this, cursorFeed);
listviewFeed.setAdapter(adapterMeasurement);
}
It is all working well. I just want to order the posts by Date or by ID.
Is there any way to sort MergeCursor?
I guess there is no way to sort the MergeCursor so I tried to think of other ways.
I changed my query like this:
public static Cursor getFeed (DBHelper dbHelper, String strUserID)
{
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursorFollowing = getFollowing(dbHelper,strUserID);
String strQuery = "SELECT * FROM feed_tbl WHERE "+ Tables.FeedTable.COLUMN_USERID + "="+strUserID;
if(cursorFollowing.getCount()>0)
{
for(int intCtr=0;intCtr<cursorFollowing.getCount();intCtr++)
{
int intUseridI = cursorFollowing.getColumnIndex(Tables.FollowTable.COLUMN_USERID);
String strUseridI = cursorFollowing.getString(intUseridI);
String strConcatQuery = " OR "+ Tables.FeedTable.COLUMN_USERID + "="+strUseridI;
if (intCtr + 1 == cursorFollowing.getCount()) {
cursorFollowing.close();
} else {
cursorFollowing.moveToNext();
}
strQuery = strQuery +""+strConcatQuery;
Log.v(TAG,strQuery);
}
}
Cursor cursor = db.rawQuery(strQuery+" ORDER BY "+ Tables.FeedTable.COLUMN_ID + " DESC",null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
The result on the log tag is this:
V/FeedMe: SELECT * FROM feed_tbl WHERE feed_userid=1 OR feed_userid=2 OR feed_userid=4 OR feed_userid=5
Just to make things clear to those who have the same problem with me which is about MergeCursor sorting. THERE IS NO SUCH WAY TO SORT MERGECURSOR :)
Thankyou!

Getting one column of SQLite DB to ListView not working in Android

I'm trying to retrieve a column (a database column where names are saved) and puting them to a listview. I have a class called Data with "getters" and "setters".
The following code is placed in a DBHandler class which extends SQLiteOpenHelper. This code is called from the MainActivity.java where the listview is meant to be updated with an onClickButton event.
public String[] getNames (int a, int b) {
String[] names = new String[] {};
String selectQuery = "SELECT * FROM " + TABLE_NAME
+ " WHERE " + KEY_ONE + " = ? AND " + KEY_TWO + " = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[]{String.valueOf(a), String.valueOf(b)});
if (cursor.moveToFirst()) {
int i = 0;
do {
Data myData = new Data();
names [i] = cursor.getString(1); //Names in cursor
++i;
} while (cursor.moveToNext());
}
return names;
}
In the MainActivity.java I call the following code before updating and notifying the update of the listview adapter:
values = db.getNames (1, 1);
I don't know why but this isn't working, it throws many errors with String lengths and crashes the app when I click the button that is suposed to enter the onClickButton.
Thanks
Follow the laalto answer and at last convert your ArrayList to Array like below:
String[] arrRecords = names.toArray(new String[names.size()]);
String[] names = new String[] {};
...
names [i] = cursor.getString(1); //Names in cursor
You're assigning to an empty array which causes ArrayIndexOutOfBoundsException.
Consider using a list such as ArrayList where you can append your values, e.g.
List<String> names = new ArrayList<String>();
...
names.add(cursor.getString(1));
If you really need to return a String[], you can convert the list with toArray():
String[] arr = new String[names.size()];
names.toArray(arr);
return arr;
Also, when posting questions that involve exceptions, always include the exception stacktrace from logcat in the question itself.
Why use like this
String[] names = new String[] {}; //no size
names [i] = cursor.getString(1); //it can work?
Use ArrayList<String>
List<String> names = new ArrayList<String>(); //declare
names.add(<column-val>); //add column value to list

display data in TextView

public List<UserDataHelper> getData() {
List<UserDataHelper> list = new ArrayList<UserDataHelper>();
String selectQuery = "SELECT * FROM " + TABLE;
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
UserDataHelper quest = new UserDataHelper();
quest.setID(cursor.getInt(0));
quest.setName(cursor.getString(1));
quest.setSent(cursor.getInt(2));
quest.setRecieved(cursor.getInt(3));
quest.setTotal(cursor.getInt(4));
quest.setTimeSpent(cursor.getString(5));
list.add(quest);
} while (cursor.moveToNext());
}
return list;
}
This is for a listView but I want to fetch data individually and display it in textView. How can I achieve that? There are a lot of tutorials for listviews but not for textViews so can someone help me out please.
try this
for (UserDataHelper user:getData())
{
textView.append(user.getID()+" "+user.getName()
+" "+user.getRecieved()+" "+user.getSent()
+" "+user.getTimeSpent()+" "+user.getTotal()+"\n");
}
You could simply use the class object to set/get values, do following for string values:-
textView.setText(quest.getName());
and for the integer values make sure to use one
of the following:-
textView.setText(""+quest.getId());
or
textView.setText(String.valueOf(integer));

Categories