ORMLite get single database column - android

I'm trying to use this SQL command with Ormlite:
select address from receive
With this code:
List<Receivers> receiver_address = receiverDao.queryBuilder().selectColumns("address").query();
But the object returned is:
1 = {Receivers#830028192208}
address = {String#830028192264} "my new address"
city = null
email = null
telephone = null
mobile = null
name_family = null
national_code = null
postal_code = null
receiver_name = null
id = 2
I need only address field in this query without iterator such as:
List<String> list = new ArrayList<String>();
for( Receivers lst:receiver_address)
list.add(lst.getAddress());
How to do this action?

You can use RawRowMapper here:
List<String> addresses = receiverDao.queryRaw("select address from receive", new RawRowMapper<String>() {
#Override
public String mapRow(String[] columnNames, String[] resultColumns) throws SQLException {
return resultColumns[0];
}
}).getResults();

Related

Is there a unique identifier for Android phone contacts?

I have an app that reads the contact details of the phone. This code returns 744 as the id of a particular contact's row when accessed through Email.ContentUri.
var uriEmail = ContactsContract.CommonDataKinds.Email.ContentUri;
string[] projectionEmail = { ContactsContract.Contacts.InterfaceConsts.Id, ContactsContract.Contacts.InterfaceConsts.DisplayName, ContactsContract.Contacts.InterfaceConsts.PhotoUri, ContactsContract.CommonDataKinds.Email.Address };
var cursorEmail = this.Activity.ContentResolver.Query(uriEmail, projectionEmail, null, null, null);
// var contactList = new List<string>();
contacts = new ObservableCollection<Contact>();
if (cursorEmail.MoveToFirst())
{
do
{
//contactList.Add(cursor.GetString(cursor.GetColumnIndex(projection[2])));
contacts.Add(new Contact()
{
Id = cursorEmail.GetInt(cursorEmail.GetColumnIndex(projectionEmail[0])),
Name = cursorEmail.GetString(cursorEmail.GetColumnIndex(projectionEmail[1])),
Photo = cursorEmail.GetString(cursorEmail.GetColumnIndex(projectionEmail[2])),
Email = cursorEmail.GetString(cursorEmail.GetColumnIndex(projectionEmail[3])),
});
}
while (cursorEmail.MoveToNext());
}
ListView listEmail = v.FindViewById<ListView>(Resource.Id.listViewSelect);
listEmail.Adapter = new ContactAdapter(v.Context, contacts);
listEmail.ItemClick += OnClientListClick;
This code returns 752 as the id of the same contact when accessed through StructuredPostal.ContentUri.
var uriAddress = ContactsContract.CommonDataKinds.StructuredPostal.ContentUri;
string[] projectionAddress = { ContactsContract.Contacts.InterfaceConsts.Id, ContactsContract.Contacts.InterfaceConsts.DisplayName, ContactsContract.Contacts.InterfaceConsts.PhotoUri, ContactsContract.CommonDataKinds.StructuredPostal.Street, ContactsContract.CommonDataKinds.StructuredPostal.Postcode };
var cursorAddress = this.Activity.ContentResolver.Query(uriAddress, projectionAddress, null, null, null);
// var contactList = new List<string>();
properties = new ObservableCollection<Property>();
if (cursorAddress.MoveToFirst())
{
do
{
int n = cursorAddress.GetInt(cursorAddress.GetColumnIndex(projectionAddress[0]));
string str = cursorAddress.GetString(cursorAddress.GetColumnIndex(projectionAddress[1]));
if (n == nId)
{
//contactList.Add(cursor.GetString(cursor.GetColumnIndex(projection[2])));
properties.Add(new Property()
{
Id = cursorAddress.GetInt(cursorAddress.GetColumnIndex(projectionAddress[0])),
Name = cursorAddress.GetString(cursorAddress.GetColumnIndex(projectionAddress[1])),
Photo = cursorAddress.GetString(cursorAddress.GetColumnIndex(projectionAddress[2])),
Street = cursorAddress.GetString(cursorAddress.GetColumnIndex(projectionAddress[3])),
Postcode = cursorAddress.GetString(cursorAddress.GetColumnIndex(projectionAddress[4])),
});
}
}
while (cursorAddress.MoveToNext());
}
ListView listAddress = v.FindViewById<ListView>(Resource.Id.listViewSelect);
listAddress.Adapter = new PropertyAdapter(v.Context, properties);
listAddress.ItemClick += OnPropertyListClick;
Is there a unique identifier that's allocated to the contact in the Android phone?
If you wanna a unique id, you could use CONTACT_ID which is a reference to _ID of each contact.
CONTACT_ID:
https://developer.android.com/reference/android/provider/ContactsContract.RawContactsColumns.html#CONTACT_ID
_ID:https://developer.android.com/reference/android/provider/BaseColumns#_ID
If you want to use the unique id cross device, you could try to use the LOOKUP_KEY.
LOOKUP_KEY:
https://developer.android.google.cn/reference/android/provider/ContactsContract.ContactsColumns.html#LOOKUP_KEY
For more code details, you could check the link below. Get cross-device unique ID for Android phone contacts

Android studio: build sqlite select query dynamically depending on values in json array

I'm working in Android studio (java).
I'm working with a sqlite database and I want to be able to query a table. I would currently use the following code:
''
String strQuery = "select * from table where var1 = ?";
SQLiteStatement stmt = sqLiteDatabase.compileStatement(strQuery);
stmt.bindString(1, String.valueOf(strVarOne));
stmt.execute();
''
But I need to dynamically build the WHERE statement. I currently have a json array which I want to use to build the where statement that looks like this (for example).
[{"country":"South Africa"},{"province":"Gauteng"}]
In the above example I would want the query to look as follows:
"select * from table where country = 'South Africa' and province= 'Gauteng' "
Can anyone assist with how I could build and run that query dynamically depending on the json array?
Bear in mind that the json array may change - the values may differ and there may be more of them.
class Place {
#SerializedName("country")
String country = null;
#SerializedName("province")
String province = null;
}
Type token = new TypeToken<ArrayList<Place>>(){}.type
String yourJson = "[{\"country":\"South Africa\"},{\"province\":\"Gauteng\"}]";
Gson gson = new Gson();
ArrayList<Place> places = gson.fromJson(yourJson, token);
String selectFormat = "select * from table where %$1s = '%$2s' and %$3s = '%$4s' "
ArrayList<String> selectArguments = new ArrayList<String>();
for(int i=0; i<places.size(); i++){
if(places.country!=null){
selectArguments.add("country");
selectArguments.add(places.country);
}else if(places.province != null) {
selectArguments.add("province");
selectArguments.add(places.province);
}
}
I will not go as far as to tell you how to avoid SQL injection.
String fullSQLStatement = String.format(selectFormat,selectArguments.toArray(new String[selectArguments.size()]);
fullSQLStatement would become select * from table where country = 'South Africa' and province = 'Gauteng'

Android Firebase Query returning nothing

Above is my firebase database:
-Ideas
--Key generated by firebase
--uid
--name
--date
--title
Now I want to get all the ideas generated by a particular uid and attach the query to the recycler. Following is my query and adapter but it returns nothing.
DatabaseReference myIdeasReference = FirebaseDatabase.getInstance().getReference();
final Query myideas =myIdeasReference.child("Ideas")orderByKey().equalTo("userUid",userUid);
mAdapter = new FirebaseRecyclerAdapter<Idea, IdeaHolder>(Idea.class, R.layout.listview_feed, IdeaHolder.class, myideas) {
#Override
public void populateViewHolder(IdeaHolder IdeaViewHolder, final Idea ideaObject, int position) {
int voteCountint = ideaObject.getvoteCount();
String voteCount = Integer.toString(voteCountint);
int flagCountint = ideaObject.getflagCount();
String flagCount = Integer.toString(flagCountint);
String title = ideaObject.gettitle();
String body = ideaObject.getBody();
String postDate = ideaObject.getPostDate();
String mfullName = ideaObject.getfullName();
//pass values :key, Ideauid and Userid to setbutton method in ideaviewholder class
DatabaseReference idearef = getRef(position);//get the database reference of the object at selected position
final String key = idearef.getKey();//get key of the idea reference to get the location later in mvote and mflag
String ideaUid = ideaObject.getuid();
P.S. I also tried the following query:
final Query myideas = myIdeasReference.child("Ideas").orderByValue().equalTo("userUid",userUid);
but then also nothing was displayed.
try with this, this should work for you
myideas = myIdeasReference.child("Ideas").orderByChild("userUid").equalTo(userUid);

Loading multiple contacts with Xamarin.Contacts.AddressBook

I want to load several contacts via Xamarin.Contacts.AddressBook, at the moment I have something like:
var loookupIDs = /* load 10 saved contact IDs */
var addressBook = new AddressBook(context) { PreferContactAggregation = true };
foreach(var id in loookupIDs)
{
var contact = addressBook.Load(id);
names.Add(contact.DisplayName);
}
However, this is really slow (tested on Android device) - even just loading 10 contacts. Is there a way to batch up the loading so it's faster? Or is the only option to use platform specific APIs instead of the Xamarin wrapper.
Yes, Xamarin.Mobile is kind of slow. It combines all possible contacts (phones, mails, etc) and all possible fields, which is not recommended by Android reference manual.
I recommend you to use native way to query your contacts with Cursor and filter it for your needs. Sadly, Xamarin dev mixed up all constants, so it is not trivial task.
Here is complete example
public class PhoneContactInfo
{
public string PhoneContactID { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
}
public IEnumerable<PhoneContactInfo> GetAllPhoneContacts(IEnumerable<int> filterIds = null)
{
Log.Debug("GetAllPhoneContacts", "Getting all Contacts");
var arrContacts = new System.Collections.Generic.List<PhoneContactInfo>();
PhoneContactInfo phoneContactInfo = null;
var uri = ContactsContract.CommonDataKinds.Phone.ContentUri;
string[] projection = { ContactsContract.Contacts.InterfaceConsts.Id,
ContactsContract.Contacts.InterfaceConsts.DisplayName,
ContactsContract.CommonDataKinds.Phone.Number
};
//String[] strings = filterIds.Select(k => Convert.ToString(k)).ToArray();
//string whereClause = ContactsContract.Contacts.InterfaceConsts.Id + " = ? ";
var cursor = MainActivity.ContextHolder.ContentResolver.Query(uri, projection,
null,
null,
null);
cursor.MoveToFirst();
while (cursor.IsAfterLast == false)
{
int phoneContactID = cursor.GetInt(cursor.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.Id));
if (filterIds.Contains(phoneContactID))
{
String contactNumber = cursor.GetString(cursor.GetColumnIndex(ContactsContract.CommonDataKinds.Phone.Number));
String contactName = cursor.GetString(cursor.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.DisplayName));
phoneContactInfo = new PhoneContactInfo()
{
PhoneContactID = Convert.ToString(phoneContactID),
ContactName = contactName,
ContactNumber = contactNumber
};
arrContacts.Add(phoneContactInfo);
}
cursor.MoveToNext();
}
cursor.Close();
cursor = null;
Log.Debug("GetAllPhoneContacts", "Got all Contacts");
return arrContacts;
}
If you wish to add some fancy async
public Task<IEnumerable<PhoneContactInfo>> GetAllPhoneContactsAsync(IEnumerable<int> filterIds)
{
return Task.FromResult(GetAllPhoneContacts(filterIds));
}
Also take a look at commented whereClause. You possibly can construct 'SQL like' where clause to make this query even more faster. Just build a string with several '=' and 'or'
P.S.
I didn't measure performance differences, if anyone has decent statistics i will be grateful
It looks like you access AdressBook for each loookupID, this might cause your speed issue.
Try:
1) Fetch all contacts, or only those you might be interested in. (Use Linq)
2) Do further work with found contacts
Example from Xamarin docs:
http://blog.xamarin.com/introducing-xamarin-contacts/
var book = new AddressBook (this) {
PreferContactAggregation = true
};
foreach (Contact c in book.Where (c => c.LastName == "Smith")) {
print (c.DisplayName);
foreach (Phone p in c.Phones)
print ("Phone: " + p.Number);
foreach (Email e in c.Emails)
print ("Email: " + e.Address);
}

Cursror into string error cursor.getcolumnIndex Key_titles and therefore cant fill my arraylist

Cursor curz=mDbHelper.fetchAllRemindersG();
startManagingCursor(curz);
ArrayList<String> mArrayList = new ArrayList<String>();
String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
for(curz.moveToFirst(); curz.moveToNext(); curz.isAfterLast())
{ mArrayList.add(name); }
name_Val = (String[]) mArrayList.toArray(new String[mArrayList.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,name_Val);
txtPhoneName.setAdapter(adapter);
I am filling a autocompletetextview and i get an error at String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
it just can't get the correct column index it forcecloses ive tried to wirte mdbHelper.KEY_TITLE or just KEY_TITLE but it was the same error
curz.moveToFirst()
String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
do {
mArrayList.add(name);
}while(curz.moveToNext());
First you need to move to first row, then you can get something from it. Because when cursor is created, the pointer points to the -1 index or you can say it points to beforeFirst.
Cursor curz=mDbHelper.fetchAllRemindersG();
startManagingCursor(curz);
// setTheme(android.R.style.Theme_Light);
curz.moveToFirst();
ArrayList<String> mArrayList = new ArrayList<String>();
if (curz.getCount() > 0)
{
do
{
String name = curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
if(name!=null)
{
mArrayList.add(name);
}
}while (curz.moveToNext());
}

Categories

Resources