I've got three table and i want make a query withe sql statement, but it does not work well because it does not give me all the possible results...
The code:
public void setsuchresultat(String pSearchword)
{
String[] table = new String[]{"tbl_A", "tbl_B", "tbl_C"};
String[] column = new String[]{"columnA", "columnB" }; // Type varchar(50) not null
String[] search = new String[]{"%" + pSearchword+ "%", pSearchword+ "%", "%" + pSearchword, pSearchword};
getdata(table,column,search);
}
public void getdata(String[] pTable, String[] pColumn, String[] pSearch)
{
for(String t:pTable)
{
for(String s : pColumn)
{
for(String k : pSearch)
{
Cursor c = this.db.rawQuery("SELECT * FROM " + t + " WHERE " + s + " LIKE '"+ k + "'", null);
if ((c.moveToFirst()) || c.getCount() > 0)
{
while(c.moveToNext())// Suchresultat abspeichern
{
String col1 = c.getString(c.getColumnIndex("columnA"));
String col2 = c.getString(c.getColumnIndex("columnB"));
}
}
}
}
}
}
I think problem is in your loop and if check.
Change
if ((c.moveToFirst()) || c.getCount() > 0)
{
while(c.moveToNext())// Suchresultat abspeichern
{
String col1 = c.getString(c.getColumnIndex("columnA"));
String col2 = c.getString(c.getColumnIndex("columnB"));
}
}
to
if (c.moveToFirst() || c.getCount() > 0) /* OR if (c != null && c.moveToFirst())*/ {
do {
String col1 = c.getString(c.getColumnIndex("columnA"));
String col2 = c.getString(c.getColumnIndex("columnB"));
} while(c.moveToNext());
}
Related
Suppose I have created a Contact with blank name ("") and entered 2 number
1234
5678
Now I want to retrieve name from this 2 number. My code always gets first number as name if name is empty. How can I get actual name?
I have used this code:
public static String getContactNamefromNumber(Context context,
String contactNumber) {
if (contactNumber == null || contactNumber.equals(""))
return null;
String name = null;
Cursor contactLookupCursor = context.getContentResolver().query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(contactNumber)),
new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID},
null, null, null);
if (contactLookupCursor != null) {
if (contactLookupCursor.moveToFirst()) {
do {
name = contactLookupCursor.getString(contactLookupCursor
.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
} while (contactLookupCursor.moveToNext());
}
contactLookupCursor.close();
}
return name;
}
This code always give me first number as name if actual contact name is blank. I want the actual name( it may blank or valid name) not number. If there is anyway to determine name is blank ? this will also solve my problem.
Added:
I also tried below code:
String name ="";
Cursor nameCur = context.getContentResolver()
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ?",
new String[] {
Long.valueOf(contactId).toString() }, null);
if (nameCur != null && nameCur.getCount() > 0 ) {
nameCur.moveToFirst();
do {
name += "" + nameCur.getPosition() + " : ";
String displayName = nameCur.getString(nameCur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (displayName == null) displayName = "";
String firstName = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
if (firstName == null) firstName = "";
String middleName = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME));
if (middleName == null) middleName = "";
String lastName = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
if (lastName == null) lastName = "";
name += "First: " + firstName + " Middle: " + middleName + " Last: " + lastName + "\n";
}while (nameCur.moveToNext());
nameCur.close();
}
Here i have used contactid to load name but not working for all contacts. For some contacts nameCur contain more than one rows(2,3,4,...8 etc). And sometime first row contains blank info . Here is a sample info i get form nameCur. For below case i got nameCur with size 9.
0 : First: Middle: Last:
1 : First: Test_Name Middle: Last: Deb
2 : First: Middle: Last:
3 : First: Middle: Last:
4 : First: Middle: Last:
5 : First: 3 Middle: Last:
6 : First: com.google Middle: Last:
7 : First: Middle: Last:
8 : First: 2 Middle: Last:
You can try
String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
I have solved this with some modification. I have added where clause
ContactsContract.Data.MIMETYPE = ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE
and sort order
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME
Here is the code i have used:
public static String getActualContactNameByContactId(Context context, long contactId){
String name ="";
String whereName = ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ? " + " AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereNameParams = new String[] { String.valueOf(contactId), ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
String sortOrder = ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME;
// get firstName & lastName
Cursor nameCur = context.getContentResolver()
.query(ContactsContract.Data.CONTENT_URI,
null,
whereName,
whereNameParams,
sortOrder);
if (nameCur != null && nameCur.getCount() > 0 ) {
nameCur.moveToFirst();
try {
nameCur.getString(nameCur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// if (displayName == null) displayName = "";
String firstName = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
if (firstName == null) firstName = "";
//Log.d("--> ", firstName.length()>0?firstName:displayName);
String middleName = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME));
if (middleName == null) middleName = "";
String lastName = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
if (lastName == null) lastName = "";
name = firstName.trim();
if (middleName.trim().length() > 0) {
if (name.length() > 0) {
name+= " ";
}
name+= middleName.trim();
}
if (lastName.trim().length() > 0) {
if (name.length() > 0) {
name+= " ";
}
name+= lastName.trim();
}
}catch (Exception e){
}finally {
nameCur.close();
}
}
return name;
}
I have taken only the first row form the cursor as multiple row may return.
I want to update a row in a SQL table in a column (`click'). I can see the row in debug but it isn't recognized.
If click==0 so change to click==1.
Does someone know what is my mistake?
My code is:
public void UpdateClicked2(String name, int table) {
ContentValues values = new ContentValues();
String selectQuery = "SELECT * FROM " + MySQLiteGUESTS.TABLE_NAME
+ " WHERE " + MySQLiteGUESTS.COLUMN_TABLE + "=" + table;
Cursor cursor = database.rawQuery(selectQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
GuestInfo comment = cursorToComment(cursor);
if (comment.getName().toString() != name)
cursor.moveToNext();
else {
if (comment.getClick() == 1) {
values.put(MySQLiteGUESTS.COLUMN_CLICK, 0);
} else
values.put(MySQLiteGUESTS.COLUMN_CLICK, 1);
}
}
String newString = MySQLiteGUESTS.COLUMN_NAME + " = " + name;
database.update(MySQLiteHelper.TABLE_NAME, values, newString, null);
}
if (comment.getName().toString() != name)
Instead of this
Use this:
if (comment.getName().toString().equals(name))
{
}
How to remove duplicate number entry in Android when fetching contact number from contact book?
For example:
In contact book for
one name multiple contact.. ex-type-home-9428060123,
type-work-9428060123, I want to fetch unique contact number from all
type,android problematically? I use below code for fetching
information:
private void getContactsDetails() {
showLoader();
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null/*selection + " AND " +
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1"*/, null, "UPPER("
+ ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
ContactString = new ArrayList<>();
if (phones != null) {
if (phones.getCount() > 0) {
tvNoContact.setVisibility(View.GONE);
while (phones.moveToNext()) {
String Name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
HashSet<String> mobileNoSet = new HashSet<String>();
if (!mobileNoSet.contains(number)){
String s = number.replaceAll("\\W", "");
String lastTenCharContact = null;
if (s != null && s.length() > 10) {
lastTenCharContact = s.substring(s.length() - 10);
} else {
lastTenCharContact = s;
}
// String substring = s.substring(Math.max(s.length() - 10, 0));
Log.d(TAG, "getContactsDetails: " + lastTenCharContact);
String image_uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
ContactString.add(lastTenCharContact);
DeviceContact contactModel = new DeviceContact(Name.toUpperCase(), lastTenCharContact, image_uri);
contactModelsList.add(contactModel);
mobileNoSet.add(number);
Log.d(TAG, "Name : " + Name + ", Number : " + number + ", Photo : " + image_uri);}
}
hideLoader();
AllContactsyncapiCall();
} else {
tvNoContact.setVisibility(View.VISIBLE);
}
} }
for remove duplicate Number just make hashset before your loop:
HashSet<String> mobileNoSet = new HashSet<String>();
Now when you put contact in model use below code:
if (!mobileNoSet.contains(number)){
String s = number.replaceAll("\\W", "");
String lastTenCharContact = null;
if (s != null && s.length() > 10) {
lastTenCharContact = s.substring(s.length() - 10);
} else {
lastTenCharContact = s;
}
// String substring = s.substring(Math.max(s.length() - 10, 0));
Log.d(TAG, "getContactsDetails: " + lastTenCharContact);
String image_uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
ContactString.add(lastTenCharContact);
DeviceContact contactModel = new DeviceContact(Name.toUpperCase(), lastTenCharContact, image_uri);
contactModelsList.add(contactModel);
mobileNoSet.add(number);
}
This is new code in which i m getting duplicate number :-
private void getContactsDetails() {
// showLoader();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null/*selection + " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1"*/, null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
ContactString = new ArrayList<>();
nameString = new ArrayList<>();
if (phones != null) {
if (phones.getCount() > 0) {
tvNoContact.setVisibility(View.GONE);
HashSet<String> mobileNoSet = new HashSet<String>();
while (phones.moveToNext()) {
String Name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (!mobileNoSet.contains(number)) {
// String s = number.replaceAll("\\W", "");
String s = number.replaceAll("[^[+]\\d]", "");
String lastTenCharContact = null;
lastTenCharContact = s;
/*if (s != null && s.length() > 10) {
lastTenCharContact = s.substring(s.length() - 10);
} else {
lastTenCharContact = s;
}*/
// String substring = s.substring(Math.max(s.length() - 10, 0));
Log.d(TAG, "getContactsDetails: " + lastTenCharContact);
String image_uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
ContactString.add(lastTenCharContact);
// nameString.add(Name);
contactModel = new DeviceContact(Name.toUpperCase(), lastTenCharContact, image_uri);
contactModelsList.add(contactModel);
mobileNoSet.add(number);
Log.d(TAG, "Name : " + Name + ", Number : " + number + ", Photo : " + image_uri);
}
}
// hideLoader();
AllContactsyncapiCall();
} else {
tvNoContact.setVisibility(View.VISIBLE);
}
}
}
I am working on a code snippet where i am storing my json encoded data into a txt file,and using following method to separate all parts and adding them into database.
public boolean addAnswersFromJSONArray() {
boolean flag = false;
Answer answer = new Answer();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "user_live.txt");
FileReader fr;
JsonReader reader;
try {
fr = new FileReader(file);
reader = new JsonReader(fr);
reader.beginArray();
reader.setLenient(true);
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("product_name")) {
answer.setProductName(reader.nextString());
} else if (name.equals("subject")) {
answer.setSubject(reader.nextString());
} else if (name.equals("month")) {
answer.setMonth(reader.nextString());
} else if (name.equals("year")) {
answer.setYear(reader.nextString());
} else if (name.equals("question")) {
answer.setQuestion(reader.nextString());
} else if (name.equals("answer")) {
answer.setAnswer(reader.nextString());
} else if (name.equals("question_no")) {
answer.setQuestion_no(reader.nextString());
} else if (name.equals("marks")) {
answer.setMarks(reader.nextString());
} else {
reader.skipValue();
}
}
answer.save(db);
reader.endObject();
flag = true;
}
reader.endArray();
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
file.delete();
db.close();
}
return flag;
}
and then i am retrieving each fields departments,subjects,month and year,questions,answers,question_no, but while retrieving marks i am getting only unique entries that is 10 and 5....Ideally the size of one set is 18 so i m getting ArrayIndexoutOfBounds Exception.
//database calling part
marks = db.getMarksList(department, subject, month_year);
database method is,
public String[] getMarksList(String department, String subject,
String month_year) {
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
String whereClause = DEPARTMENT + " = '" + department + "'" + " AND "
+ SUBJECT + " = '" + subject + "' AND " + MONTH + " = '"
+ month + "' AND " + YEAR + " = '" + year + "'";
System.out.println("questions: " + whereClause);
Cursor cursor = db.query(true, "ANSWERS", new String[] { "MARKS" },
whereClause, null, null, null, "DEPARTMENT", null);
String list[] = new String[cursor.getCount()];
int i = 0;
if (cursor != null && cursor.getCount() > 0) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
list[i] = new String(cursor.getString(0));
i++;
}
}
return list;
}
Can anyone help me to resolve this issue?? Why getting only unique value,I have checked my json result also each row contains marks.
i got the solution for this,
Changed database query and method as following,
public List<Answer> getMarksList(String department, String subject,
String month_year) {
List<Answer> list = new ArrayList<Answer>();
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
try {
String sql1 = "select all marks from " + TABLE_NAME
+ " where department = '" + department
+ "' AND subject = '" + subject + "' AND month = '" + month
+ "' AND year = '" + year + "';";
SQLiteDatabase db1 = this.getWritableDatabase();
Cursor cursor = db1.rawQuery(sql1, null);
if (cursor.moveToFirst()) {
do {
Answer a = new Answer();
a.setMarks(cursor.getString(0));
list.add(a);
} while (cursor.moveToNext());
}
} catch (Exception e) {
}
return list;
}
using "all" in query is retrieving all records.
I am trying to do Order by to fetch the records from higher to lower values , but the sorting is not happening, i am getting the records randomly.
Here is my code , please let me know , where i am going wrong:
public void fetchTopRecords() {
int i = 0;
String where = "SELECT * FROM " + DATABASE_TABLE_2 + " ORDER BY "
+ COL_C + " ASC LIMIT 6";
Cursor c = db.rawQuery(where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
String pckname = c.getString(COL_A);
array_pck.add(pckname);
int marks = c.getInt(COL_C);
i++;
} while (c.moveToNext());
}
}
use the below code it will work :
public void fetchTopRecords() {
String where = "SELECT * FROM " + DATABASE_TABLE_2 + " ORDER BY "
+ COL_C + " DESC LIMIT 6";
Cursor c = db.rawQuery(where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
String pckname = c.getString(COL_A);
array_pck.add(pckname);
int marks = c.getInt(COL_C);
} while (c.moveToNext());
}
}