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);
Related
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);
}
}
I have an book mark option in my application, here to sort in SQLITE by "order by" using selected set of column values (ID) like: order by (ID=1,5,4,3) so I would get record 1, 5, 4, 3 in that order out,
But it show id=1,2,3,4,5 in listview please any one help me.
databasehelper activity
public Cursor getBookMarks() {
try{
SQLiteDatabase db =myDataBase;// getReadableDatabase();
SQLiteQueryBuilder qb1 = new SQLiteQueryBuilder();
String [] sqlSelect1 = {"0 _id", KEY_NAME,KEY_PH_NO,KEY_ID};
String sqlTables1 = TABLE_BOOKMARK;
String strQuery1=KEY_PH_NO+"='1'";
strOrder1=KEY_ID + " DESC";
qb1.setTables(sqlTables1);
String strvalues="";
Cursor curs = qb1.query(db, sqlSelect1, strQuery1, null,null, null, strOrder1);
if(curs!=null)
{
curs.moveToFirst();
if(curs.getCount()>=1)
{
do
{
strvalues+=""+curs.getString(curs.getColumnIndex(KEY_NAME))+",";
}
while (curs.moveToNext());
if(strvalues.length()>=1)
{
strvalues+="-1";
String [] sqlSelect = {"0 _id", "TB","Version","Book","Chapter","NKJ"};
String sqlTables = "hindibible";
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(sqlTables);
String strOrderbook="Book" + " desc";
StringBuilder strQuery = new StringBuilder();
strQuery.append("ID IN (" +strvalues + ")");
StringBuilder strOrderBy = new StringBuilder();
strOrderBy.append(" CASE ID ");
String [] arrIDs = strvalues.split(",");
for(int i=0;i<arrIDs.length;i++)
{
strOrderBy.append(" WHEN " + arrIDs[i] + " THEN " + arrIDs[i]);
}
strOrderBy.append(" END");
Cursor bible = qb.query(db, sqlSelect, strQuery.toString(), null,null, null, strOrderBy.toString());
bible.moveToFirst();
return bible;
}
}
else
{
}
}
else
{
}
}catch (Exception e) {
Log.d("setBookMark",e.toString());
}
return null;
}
I am trying this
if(curs!=null)
{
List<Cursor> listCursor = new ArrayList<Cursor>();
curs.moveToFirst();
if(curs.getCount()>=1)
{
do
{
String strID = curs.getString(curs.getColumnIndex(KEY_NAME));
String [] sqlSelect = {"0 _id", "TB", "Version", "Book", "Chapter", "NKJ"};
String sqlTables = "hindibible";
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(sqlTables);
StringBuilder strQuery = new StringBuilder();
strQuery.append("ID = "+strID);
Cursor bible = qb.query(db, sqlSelect, strQuery.toString(), null,null, null,null);
listCursor.add(bible);
}while (curs.moveToNext());
return listCursor;
}
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);
}
}
}
Actually I am using call logs as an input to database and then I am fetching it in a way that I can't get any duplicate values while displaying it and if i have any duplicate value in data base then it should be taken as integer value count. For example: john(6).
Here john must have entry 6 times in database. Don't get me wrong. I don't need a code.I need help. Here is code:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(android.provider.CallLog.Calls.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String rawContactId = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls._ID));
Cursor callLogCursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, new String[]{
android.provider.CallLog.Calls.CACHED_NAME,
android.provider.CallLog.Calls.CACHED_NUMBER_LABEL,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.DATE,
android.provider.CallLog.Calls.DURATION,
android.provider.CallLog.Calls.TYPE
},android.provider.CallLog.Calls._ID + "=?", new String[] { rawContactId }, null);;
if (callLogCursor != null) {
while (callLogCursor.moveToNext()) {
//String id = callLogCursor.getString(0);
String name = callLogCursor.getString(0);
String cacheNumber = callLogCursor.getString(1);
String number = callLogCursor.getString(2);
long dateTimeMillis = callLogCursor.getLong(3);
long durationMillis = callLogCursor.getLong(4);
int callType = callLogCursor.getInt(5);
String duration = getDuration(durationMillis * 1000);
String dateString = getDateTime(dateTimeMillis);
if (cacheNumber == null)
cacheNumber = number;
if (name == null)
name = "Unknown";
Uri image = null;
try {
String conId = fetchContactIdFromPhoneNumber(cacheNumber);
long contId = Long.parseLong(conId);
image = getPhotoUri(contId);
}catch(Exception e) {
Log.e("Exception", e.getMessage());
}
//CallLogModel callLogModel = new CallLogModel(image, name, cacheNumber,
// duration, dateString);
ContentValues values = new ContentValues();
values.put(NAME, name);
values.put(NUMBER, cacheNumber);
values.put(DATE, dateString);
values.put(DURATION,duration );
database.insert(CALL_LOG_TABLE, null, values);
Cursor cursor = database.query(CALL_LOG_TABLE, new String [] {LOG_ID, NAME, NUMBER, DATE, DURATION}, null, null, null, null, null);
int row =0;
if(!cursor.isAfterLast()) {
cursor.moveToFirst();
do{
int pId=cursor.getInt(0);
String pName = cursor.getString(1);
String pNumber = cursor.getString(2);
String pDate = cursor.getString(3);
String pDuration = cursor.getString(4);
int value = 0;
CallLogModel callLogModel = new CallLogModel(image, name, cacheNumber, duration, dateString);
if (callType == CallLog.Calls.OUTGOING_TYPE) {
for(int i=0;i<outgoingList.size();i++){
------------------------------Actually i want Logic here what should i do here--------------
}
}
outgoingList.add(callLogModel);
} else if (callType == CallLog.Calls.INCOMING_TYPE) {
incomingList.add(callLogModel);
} else if (callType == CallLog.Calls.MISSED_TYPE) {
missedcallList.add(callLogModel);
}
cursor.moveToNext();
} while (!cursor.isAfterLast());
}
}
callLogCursor.close();
}
}
You could model the outgoing calls in a hashmap, something like:
Map<String, Integer> outgoingCallsMap = new HashMap<String, Integer>();
for (int i = 0; i < outgoingList.size(); i++) {
String nameOfCallee = outgoingList.get(i);
if (!outgoingCallsMap.containsKey(nameOfCallee)) {
outgoingCallsMap.put(nameOfCallee, 1);
} else {
//Increment calls to this person
outgoingCallsMap.put(nameOfCallee, outgoingCallsMap.get(nameOfCallee) + 1);
}
}
Remove the duplicates in your outGoingList, by iterating it and putting the result to a map, with contact name as key and list of CallLogModel object as value.
You can refer this method.
private void convertToOutGoingMap(List<CallLogModel > outGoingList) {
HashMap<String,List<CallLogModel>> outGoingMap = new HashMap<String, List<CallLogModel>>();//map which has CallLogModel.name as key and List<CallLogModel> as value.
for(CallLogModel model : outGoingList){//Iterate thru the list.
if(outGoingMap.containsKey(model.name))
{
outGoingMap.get(model.name).add(model);//if map contains key, add model to the list.
} else {
List<CallLogModel> modelList = new ArrayList<CallLogModel>();//if it does not contains, initialize a list and add model to it.
modelList.add(model);
outGoingMap.put(model.name, modelList);
}
}
}
}
The key set of this map gives you the unique call log names and corresponding value list gives all occurrences and its size gives you number of occurrences.
Hope this help you.
i got no idea why it return me nullpointerexception. I think is because the table don't have data. So, the data seem like did not add into database
this is my activity class.
private void createdata(){
String title[] = {"rancangan1", "rancangan2", "rancangan3", "rancangan4", "rancangan5"};
String date[] = {"isnin", "selasa", "rabu", "khamis", "jumaat"};
String time[] = {"17:00-18:00", "18:00-19:00", "17:00-18:00", "18:00-19:00", "19:00-20:00"};
String channel[] = {"astro ria", "astro ria", "astro ria", "astro ria", "astro ria"};
try{
for(int i = 0; i < title.length; i++){
ContentValues values = new ContentValues();
values.put(ImamShareData.DataContent.KEY_PROGRAM_TITLE, title[i]);
values.put(ImamShareData.DataContent.KEY_PROGRAM_DATE, date[i]);
values.put(ImamShareData.DataContent.KEY_PROGRAM_TIME, time[i]);
values.put(ImamShareData.DataContent.KEY_PROGRAM_CHANNEL, channel[i]);
cr.insert(ImamShareData.DataContent.PROGRAM_URI, values);
//Log.i(TAG, "Successfully added index " + i + " as ID " + mId[i]);
}
}catch(Exception e){
Log.v("error",""+e);
}
}
private void filldata(){
String[] from = new String[]{ImamShareData.DataContent.KEY_PROGRAM_DATE, ImamShareData.DataContent.KEY_PROGRAM_TIME, ImamShareData.DataContent.KEY_PROGRAM_CHANNEL};
String[] from1 = new String[]{ImamShareData.DataContent.KEY_PROGRAM_TITLE};
int[] to = new int[]{R.id.programdate, R.id.programtime, R.id.programchannel};
int[] to1 = new int[]{R.id.programtitle};
SimpleExpandableListAdapter SEL = new SimpleExpandableListAdapter(this,
createGroupList(), R.layout.programgroup_row, from1, to1,
createChildList(), R.layout.programchild_row, from, to);
setListAdapter( SEL );
}
private List createGroupList() {
String[] column = new String[]{ImamShareData.DataContent.KEY_PROGRAM_TITLE};
ArrayList result = new ArrayList();
String title[] = null;
for( int i = 1 ; i <= 5; ++i ) {
Cursor cursor = managedQuery(ImamShareData.DataContent.PROGRAM_URI, column, null, null, null);
HashMap m = new HashMap();
title[i] = cursor.getColumnName(cursor.getColumnIndex(ImamShareData.DataContent.KEY_PROGRAM_TITLE));
m.put(ImamShareData.DataContent.KEY_PROGRAM_TITLE, title[i]);
result.add( m );
}
return result;
}
private List createChildList() {
String date;
String time;
String channel;
String[] column = new String[]{ImamShareData.DataContent.KEY_PROGRAM_DATE, ImamShareData.DataContent.KEY_PROGRAM_TIME, ImamShareData.DataContent.KEY_PROGRAM_CHANNEL};
ArrayList result = new ArrayList();
for( int i = 1 ; i <= 5 ; ++i ) {
ArrayList secList = new ArrayList();
for( int n = 0 ; n < 3 ; n+=3 ) {
Cursor cursor = managedQuery(ImamShareData.DataContent.PROGRAM_URI, column, null, null, null);
HashMap child = new HashMap();
date = cursor.getColumnName(cursor.getColumnIndex(ImamShareData.DataContent.KEY_PROGRAM_DATE));
time = cursor.getColumnName(cursor.getColumnIndex(ImamShareData.DataContent.KEY_PROGRAM_TIME));
channel = cursor.getColumnName(cursor.getColumnIndex(ImamShareData.DataContent.KEY_PROGRAM_CHANNEL));
child.put(ImamShareData.DataContent.KEY_PROGRAM_DATE, date);
child.put(ImamShareData.DataContent.KEY_PROGRAM_TIME, time);
child.put(ImamShareData.DataContent.KEY_PROGRAM_CHANNEL, channel);
secList.add( child );
}
result.add( secList );
}
return result;
}
this is my contentprovider class
#Override
public Uri insert(Uri uri, ContentValues initialvalues) {
TableNumber = sUriMatcher.match(uri);
if( TableNumber != PROGRAM){
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if(initialvalues != null){
values = new ContentValues(initialvalues);
}else{
values = new ContentValues();
}
SQLiteDatabase mDb = mDbHelper.getWritableDatabase();
long rowId = mDb.insert(DatabaseHelper.TABLE_PROGRAM, null, values);
if(rowId > 0){
Uri programUri = ContentUris.withAppendedId(ImamShareData.DataContent.PROGRAM_URI, rowId);
getContext().getContentResolver().notifyChange(programUri, null);
return programUri;
}
throw new IllegalArgumentException("Failed to insert row into " + uri);
}
this is my datasharing class
public static final class DataContent implements BaseColumns{
public static final Uri PROGRAM_URI = Uri.parse("content://" + AUTHORITY + "/" + PROGRAMPATH);
public static final String CONTENT_MORE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.android.imammuda";
public static final String CONTENT_ONE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.android.imammuda";
public static final String KEY_PROGRAM_ID = "_id";
public static final String KEY_PROGRAM_TITLE = "ProgramTitle";
public static final String KEY_PROGRAM_DATE = "ProgramDate";
public static final String KEY_PROGRAM_TIME = "ProgramTime";
public static final String KEY_PROGRAM_CHANNEL = "ProgramChannel";
}
this is my logcat
05-12 16:05:46.024: ERROR/AndroidRuntime(5175): Caused by: java.lang.NullPointerException
05-12 16:05:46.024: ERROR/AndroidRuntime(5175): at com.android.imammuda.Program.createGroupList(Program.java:112)
05-12 16:05:46.024: ERROR/AndroidRuntime(5175): at com.android.imammuda.Program.filldata(Program.java:82)
You have not initialized your title variable in method createGroupList:
String title[] = null;
...
title[i] = cursor.getColumnName....
in the for loop the length is hard coded to maximum 5, so the easiest fix is:
String[] title = new String[5];