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.
Related
I am using the following method to query my SQLite database with LIKE statement.
public List<Bean> getWords(String englishWord) {
if(englishWord.equals(""))
return new ArrayList<Bean>();
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " LIKE ? ORDER BY LENGTH(" + ENGLISH + ") LIMIT 100";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{"%" + englishWord.trim() + "%"});
List<Bean> wordList = new ArrayList<Bean>();
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
wordList.add(new Bean(english, bangla));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
I would like to change the above code for that it will query for exact match. I tried to modify the code as below but I do not how to get the mal string.
public void getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{englishWord});
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
}
} finally {
if (cursor != null)
cursor.close();
}
}
Method getoneWords for what. You should return mal and english in this function.
return new Bean(english, mal);
If you need first word, just cursor.moveToFirst and delete while loop:
String english = cursor.getString(1);
String mal = cursor.getString(2);
return new Bean(english, mal);
I finally solved this problem myself.
public String getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
String meaning = "";
try {
cursor = db.rawQuery(sql, new String[] {englishWord});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
meaning = cursor.getString(2);
}
return meaning;
}finally {
cursor.close();
}
}
In your getoneWords() you are not returning the queried values.
As you have two return values you would either need to wrap them in a Pair or create a "holder" Object (e.g. class Words(String english, String mal)) for the return values.
If your Query returns multiple matches you would need to return a list of those Objects. Otherwise, your above Code would just return the last match.
So you need to alter your function to return the queried
public Pair<String,String> getoneWords(String englishWord) {
Pair<String,String> result = null;
...
if(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
result = new Pair<String,String>(english, mal);
}
...
return result;
}
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 get the following error
"E/Sync: java.text.ParseException: Unparseable date: "" (at offset 0)"
I have gone through many solutions in stack overflow. But unable to get the appropriate solution
Following is the code:
public void execute() {
if (mTableName.contentEquals("removed")) {
String query = "Select * from removed";
Cursor cursor = LODatabaseUtility.getInstance().cursorFromQuery(
query);
List<String> tableName = LODatabaseUtility.getInstance()
.dataListfromCursor(cursor, "table_name");
cursor = LODatabaseUtility.getInstance().cursorFromQuery(query);
List<String> number = LODatabaseUtility.getInstance()
.dataListfromCursor(cursor, "number");
cursor = LODatabaseUtility.getInstance().cursorFromQuery(query);
List<String> removedTimestamp = LODatabaseUtility.getInstance()
.dataListfromCursor(cursor, "timestamp");
if (number.size() == 0 || tableName.size() == 0) {
cursor.close();
}
for (int i = 0; i < tableName.size(); ++i) {
query = "Select timestamp from " + tableName.get(i) + " where "
+ tableName.get(i) + "_id = " + number.get(i);
cursor = LODatabaseUtility.getInstance().cursorFromQuery(query);
String tableTimestamp = LODatabaseUtility.getInstance()
.dataStringfromCursor(cursor);
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date removedDate, tableDate;
removedDate = df.parse(removedTimestamp.get(i));
tableDate = df.parse(tableTimestamp);
if (removedDate.compareTo(tableDate) > 0) {
query = "Delete from " + tableName.get(i) + " where "
+ tableName.get(i) + "_id = " + number.get(i);
LODatabaseUtility.getInstance().getDatabase()
.execSQL(query);
}
} catch (ParseException e) {
Log.e("Sync", "" + e);
e.printStackTrace();
}
}
cursor.close();
}
getSyncTimeFromServer(mTableName);
}
I get the error pointing to the following line of code:
tableDate = df.parse(tableTimestamp);
Only for a particular table the timestamp value is giving the error. For the rest of the tables that I have the timestamp value, the value is inserted properly. Any help would be useful
I use the below code to search the exact string in the database. For example, if I would like to search for "abc", then I need to enter "abc".
What I intend to do is to enable the searching without the exact string. For example, I can enter "bc" and return the "abc" as the result. I tried to change the englishWord.equals("") to englishWord.contains(""). However, this is not work.
public List<Bean> getWords(String englishWord) {
if(englishWord.equals(""))
return new ArrayList<Bean>();
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " LIKE ? ORDER BY " + ENGLISH + " LIMIT 100";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{englishWord + "%"});
List<Bean> wordList = new ArrayList<Bean>();
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String english = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Bean(id, english, bangla, status));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
Relace
cursor = db.rawQuery(sql, new String[]{englishWord + "%"});
with
cursor = db.rawQuery(sql, new String[]{"%" + englishWord + "%"});
Try this. Use ("%" + englishWord + "%").The code is
public List<Word> getWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " LIKE ? ORDER BY " + ENGLISH + " LIMIT 100";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{"%" + englishWord + "%"});//Change here
List<Word> wordList = new ArrayList<Word>();
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String english = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Word(id, english, bangla, status));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
I am trying to create a app which will fetch details of Events and Attendeesfrom Calendar app.
I am facing the problems which are"
1). In many of the events Title and their attendees does not match.
2). In many of the events I am getting 0 attendees
(mainly for upcoming events).
Here is my code: (Please let me know the mistake).
public class ReadCalendar {
static Cursor cursor;
public static void readCalendar(Context context) {
ContentResolver contentResolver = context.getContentResolver();
// Fetch a list of all calendars synced with the device, their display names and whether the
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/calendars"),
(new String[] { Calendars._ID, Calendars.NAME}), null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
try
{
System.out.println("Count="+cursor.getCount());
if(cursor.getCount() > 0)
{
System.out.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext()) {
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
//Boolean selected = !cursor.getString(2).equals("0");
System.out.println("Id: " + _id + " Display Name: " + displayName);
calendarIds.add(_id);
}
}
}
catch(AssertionError ex)
{
ex.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
// For each calendar, display all the events from the previous week to the end of next week.
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
//Uri.Builder builder = Uri.parse("content://com.android.calendar/calendars").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.DAY_IN_MILLIS * 10000);
ContentUris.appendId(builder, now + DateUtils.DAY_IN_MILLIS * 10000);
Log.e("123", "Calender ID---->>>>>>"+id);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { Events.TITLE, "begin", "end", "allDay", Events._ID, Events.CALENDAR_ID}, Events.CALENDAR_ID+"=" + id,
null, "_id ASC");
Log.e("123","eventCursor count====="+eventCursor.getCount());
if(eventCursor.getCount()>0)
{
if(eventCursor.moveToFirst())
{
do
{
Object mbeg_date,beg_date,beg_time,end_date,end_time;
final String title = eventCursor.getString(0);
final Date begin = new Date(eventCursor.getLong(1));
final Date end = new Date(eventCursor.getLong(2));
final Boolean allDay = !eventCursor.getString(3).equals("0");
final String eventId = eventCursor.getString(4);
final String calendarID = eventCursor.getString(5);
Log.e("123", "Event Id----->>>>>"+eventId+"---------calendarId----->>>"+calendarID);
/* System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
" All Day: " + allDay);
*/
Log.e("123","Title:"+title);
Log.e("123","Begin:"+begin);
Log.e("123","End:"+end);
Log.e("123","All Day:"+allDay);
// Attendees Code
Cursor eventAttendeesCoursor = contentResolver.query(CalendarContract.Attendees.CONTENT_URI, new String []{ Attendees.ATTENDEE_NAME, Attendees.EVENT_ID}, Attendees.EVENT_ID +" = " + eventId, null, null);
Log.e("123", "Count of no of attendees-----"+eventAttendeesCoursor.getCount());
if(eventAttendeesCoursor.getCount()>0)
{
if(eventAttendeesCoursor.moveToFirst())
{
do {
// Log.e("123", "Attendees Name---->>>"+ eventAttendeesCoursor.getString(0));
Log.e("123", "Attendees Event ID---->>>"+ eventAttendeesCoursor.getString(1));
} while(eventAttendeesCoursor.moveToNext());
}
}
}
while(eventCursor.moveToNext());
}
}
break;
}
}
}