i am building an quiz app i want to retrieve 10 questions randomly from 100 question in database.
here is the code from where i am retrieving question from database
QuizDbHelper dbHelper = new QuizDbHelper(this);
questionList = dbHelper.getQuestions(difficulty);
questionCountTotal = questionList.size();
Collections.shuffle(questionList);
QuizDbHelper class getQuestions method:
public ArrayList<Question> getQuestions(String difficulty) {
ArrayList<Question> questionList = new ArrayList<>();
db = getReadableDatabase();
String[] selectionArgs=new String[]{difficulty};
Cursor c = db.rawQuery("SELECT * FROM " + QuestionsTable.TABLE_NAME+ " WHERE " +QuestionsTable.COLUMN_DIFFICULTY+"= ?", selectionArgs);
if (c.moveToFirst()) {
do {
Question question = new Question();
question.setQuestion(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_QUESTION)));
question.setOption1(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION1)));
question.setOption2(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION2)));
question.setOption3(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION3)));
question.setOption4(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION4)));
question.setAnswerNr(c.getInt(c.getColumnIndex(QuestionsTable.COLUMN_ANSWER_NR)));
question.setDifficulty(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_DIFFICULTY)));
questionList.add(question);
} while (c.moveToNext());
}
c.close();
return questionList;
}
when i run this all the 100 questions are appering
anyone to fix it better..
First Retrieve all questions from database in Arraylist of Question
then shuffle your arraylist.
Collections.shuffle(questionList);
and sublist to 10 like
questionList.subList(0,10)
you can change your function as
public ArrayList<Question> getQuestions(String difficulty,int size,boolean random) {
ArrayList<Question> questionList = new ArrayList<>();
db = getReadableDatabase();
String[] selectionArgs=new String[]{difficulty};
Cursor c = db.rawQuery("SELECT * FROM " + QuestionsTable.TABLE_NAME+ " WHERE " +QuestionsTable.COLUMN_DIFFICULTY+"= ?", selectionArgs);
if (c.moveToFirst()) {
do {
Question question = new Question();
question.setQuestion(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_QUESTION)));
question.setOption1(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION1)));
question.setOption2(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION2)));
question.setOption3(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION3)));
question.setOption4(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION4)));
question.setAnswerNr(c.getInt(c.getColumnIndex(QuestionsTable.COLUMN_ANSWER_NR)));
question.setDifficulty(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_DIFFICULTY)));
questionList.add(question);
} while (c.moveToNext());
}
c.close();
if(random)
Collections.shuffle(questionList);
if(size > 0 && size < questionList.size()){
Collection<Question> collection = questionList.subList(0, size)
ArrayList<Question> subList = new ArrayList<>();
subList.addAll(collection);
return subList;
}
return questionList;
}
Related
How should I implement into getRow2() to get the selected row of number? So that I can moveToPosition(x);
MainActivity.java as below:
Database db = new Database(this);
int x = db.getRow2();
Cursor cursor = db.getName();
cursor.moveToPosition(x);
tvName.setText(cursor.getString(0));
Database.java as below:
public int getRow2(){
SQLiteDatabase db = this.getReadableDatabase();
int rows = -1;
try {
rows = (int) db.compileStatement("SELECT COUNT(*) FROM " + TBL_USER).simpleQueryForLong();
} catch (NullPointerException e) {
return -1;
}
return rows;
}
public Cursor getName(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select name from TBL_USER",null);
return cursor;
}
Solved:
Use moveToNext() instead of moveToPosition()
What a simple question 😚
I have gone through a lot of posts but didn't find any answer that answers the question efficiently or even correctly. The closest I came was this How to avoid duplicate contact name (data ) while loading contact info to listview? but this has too much overhead. Is there any simpler or more efficient way to solve this?
I had the same problem you had: I was getting duplicate phone numbers. I solved this problem by obtaining the normalized number for each cursor entry and using a HashSet to keep track of which numbers I'd already found. Try this:
private void doSomethingForEachUniquePhoneNumber(Context context) {
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
//plus any other properties you wish to query
};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
} catch (SecurityException e) {
//SecurityException can be thrown if we don't have the right permissions
}
if (cursor != null) {
try {
HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
int indexOfNormalizedNumber = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER);
int indexOfDisplayName = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexOfDisplayNumber = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (cursor.moveToNext()) {
String normalizedNumber = cursor.getString(indexOfNormalizedNumber);
if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {
String displayName = cursor.getString(indexOfDisplayName);
String displayNumber = cursor.getString(indexOfDisplayNumber);
//haven't seen this number yet: do something with this contact!
} else {
//don't do anything with this contact because we've already found this number
}
}
} finally {
cursor.close();
}
}
}
After API 21 We Write this Query for remove contact duplicacy.
String select = ContactsContract.Data.HAS_PHONE_NUMBER + " != 0 AND " +
ContactsContract.Data.MIMETYPE
+ " = " + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "
AND "+ ContactsContract.Data.RAW_CONTACT_ID + " = " +
ContactsContract.Data.NAME_RAW_CONTACT_ID;
Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, select,
null, null);
ContentResolver cr = this.getContentResolver();
String[] FieldList = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,FieldList,
null,null,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name,phone,ContactID;
HashSet<String> normalizedNumbers = new HashSet<>();
if(c!=null)
{
while(c.moveToNext()!=false)
{
phone = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
if(normalizedNumbers.add(phone)==true)
{
name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
ContactID = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
MyContacts m = new MyContacts(name,phone,ContactID);
ContactList.add(m);
}
}
c.close();
I am using Contact picker library for selecting multiple contacts but if a contact doesn't contain any number and if it is selected then it is showing some null pointer exception in the edit text field. How to remove that message and also how to remove trailing comma. Below is my Code.
try {
int pos = 0;
for (Contact contact : contacts) {
String displayName = contact.getDisplayName();
result.append(displayName + ",");
result.setSpan(new BulletSpan(15), pos, pos + displayName.length() + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//pos += displayName.length() + 1;
}
}
catch (Exception e) {
result.append(e.getMessage());
}
contactsView.setText(result);
please try to check this code
void getAllContacts() {
ArrayList<String> nameList = new ArrayList<>();
ArrayList<String> numberList = new ArrayList<>();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER;
String[] list = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.Contacts._ID};
Cursor cursor = getContentResolver().query(uri, list, selection, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
String contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
contactNuber.add(contactNumber);
contactsName.add(contactName);
nameList.add(contactName);
numberList.add(contactNumber);
} while (cursor.moveToNext());
cursor.close();
myContacts.put("name", nameList);
myContacts.put("number", numberList);
}
}
Hi I have this code which retrieves data from the SQLite local database I have created.
the code below is a public cursor which retrieves all the data i require from the database
public Cursor RetriveAdvertData (DatabasOpperations DBOpp, String Username, String AdvertType){
SQLiteDatabase SQDB = DBOpp.getReadableDatabase();
String[] Coloumns = {TableData.TableInfo.USERNAME, TableData.TableInfo.ADVERT_NAME, TableData.TableInfo.ADVERT_EMAIL, TableData.TableInfo.ADVERT_ADDRESS, TableData.TableInfo.ADVERT_NUMBER, TableData.TableInfo.ADVERT_TYPE};
String Where = TableData.TableInfo.USERNAME + " LIKE ? AND " + TableData.TableInfo.ADVERT_TYPE + " LIKE ?";
String Argument[] = {Username, AdvertType};
Cursor Cur = SQDB.query(TableData.TableInfo.TABLE_NAME2, Coloumns, Where, Argument, null, null, null);
return Cur;
}
I then call that Cursor in another java page
Context Contx = this;
public DatabasOpperations DB = new DatabasOpperations(Contx);
public Cursor Cur;
Cur = DB.RetriveAdvertData(DB, DBUsername, "Restaurant");
String AdName = "";
String AdEmail = "";
String AdAddress = "";
String AdNumber = "";
String AdType = "";
if (Cur.moveToFirst()){
do {
AdName = Cur.getString(Cur.getColumnIndex("AdvertsName"));
AdEmail = Cur.getString(Cur.getColumnIndex("AdvertEmail"));
AdAddress = Cur.getString(Cur.getColumnIndex("AdvertAddress"));
AdNumber = Cur.getString(Cur.getColumnIndex("AdvertNumber"));
AdType = Cur.getString(Cur.getColumnIndex("AdvertType"));
final String[] Adverts = new String[]{
AdName, AdEmail, AdAddress, AdNumber, AdType
};
ArrayAdapter setListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Adverts);
LV1.setAdapter(setListAdapter);
}while (Cur.moveToNext());
}
Cur.close();
the code does display only one row from the database, how do i amend the code to display all the rows in the database?
Try to put the setAdapter out of the while loop:
List<String[]> arr = new ArrayList<>();
if (Cur.moveToFirst()) {
do {
AdName = Cur.getString(Cur.getColumnIndex("AdvertsName"));
AdEmail = Cur.getString(Cur.getColumnIndex("AdvertEmail"));
AdAddress = Cur.getString(Cur.getColumnIndex("AdvertAddress"));
AdNumber = Cur.getString(Cur.getColumnIndex("AdvertNumber"));
AdType = Cur.getString(Cur.getColumnIndex("AdvertType"));
final String[] Adverts = new String[]{
AdName, AdEmail, AdAddress, AdNumber, AdType
};
arr.add(Adverts)
} while (Cur.moveToNext());
}
Cur.close();
ArrayAdapter setListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arr);
LV1.setAdapter(setListAdapter);
I'm looking to export the contacts that are stored in the native database.
I'm having trouble retrieving contacts from native database.
Here is the query I would like to use :
Get all the contacts that have at least a phone number or an email.
Here is the query I am using :
String dataWhere = ContactsContract.Data.MIMETYPE + "=? OR " + ContactsContract.Data.MIMETYPE + "=?";
String[] dataWhereValues = new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
String[] dataProjection = new String[]{ContactsContract.Data.CONTACT_ID, ContactsContract.Data.LOOKUP_KEY, ContactsContract.Data.DISPLAY_NAME_PRIMARY, ContactsContract.Data.STARRED, ContactsContract.Data.MIMETYPE, ContactsContract.Data.DATA1, ContactsContract.Data.DATA2, ContactsContract.Data.DATA_VERSION};
Cursor data = getContentResolver().query(ContactsContract.Data.CONTENT_URI, dataProjection, dataWhere, dataWhereValues, ContactsContract.Data.CONTACT_ID);
But this query gives me lots of weird contacts, and some of my contacts are also missing...
Can anyone help me please ?
this may help you for getting phone numbers and display names...
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
// importing phone contacts
while (phones.moveToNext())
{
listMobileNo.add(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
listName.add(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
}
phones.close();
Here is the query I ended up with
String where = ContactsContract.Data.MIMETYPE + "=? OR " + ContactsContract.Data.MIMETYPE + "=?";
String[] whereValues = new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE};
String[] dataProjection = new String[]{ContactsContract.Data.CONTACT_ID, ContactsContract.Data.LOOKUP_KEY, ContactsContract.Data.DISPLAY_NAME_PRIMARY, ContactsContract.Data.STARRED, ContactsContract.Data.MIMETYPE, ContactsContract.Data.DATA1, ContactsContract.Data.DATA2, ContactsContract.Data.DATA_VERSION};
Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, dataProjection, dataWhere, dataWhereValues, ContactsContract.Data.CONTACT_ID + " ASC");
int cidIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.CONTACT_ID);
int nameIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.DISPLAY_NAME_PRIMARY);
int starredIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.STARRED);
int typeIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE);
int data1Index = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA1);
int data2Index = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA2);
int lookupKeyIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.LOOKUP_KEY);
int versionIndex = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA_VERSION);
boolean hasData = cursor.moveToNext();
while (hasData){
contactId = cursor.getLong(cidIndex);
nativeLookupKey = cursor.getString(lookupKeyIndex);
fullName = cursor.getString(nameIndex);
starred = cursor.getInt(starredIndex);
version = cursor.getLong(versionIndex);
while (currentContactId <= contactId && hasData) {
if (currentContactId == contactId) {
String type = cursor.getString(typeIndex);
if (type.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
String email = cursor.getString(data1Index);
} else if (type.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
String number = cursor.getString(data1Index);
}
}
hasData = cursor.moveToNext();
if (hasData) {
currentContactId = cursor.getLong(cidIndex);
}
}
}