How to retrieve contact number from phonebook in android? - java

/This is my override function. It works fine when I just retrieve names from the phone book. But the app crashes the moment i try to retrieve a contact number./
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (1) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if(c.moveToFirst()) {
String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (hasPhone.equalsIgnoreCase("1"))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
phones.moveToFirst();
String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(getApplicationContext(), cNumber, Toast.LENGTH_SHORT).show();
}
}
c.close();
}
break;
}
}

First of all, create POJO class.
public class ContactEntity {
String name;
String number;
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
Now, to retrieve contacts.
ArrayList<ContactEntity> contactList = new ArrayList<>();
contactList = getcontactList();
public ArrayList<ContactEntity> getcontactList() //This Context parameter is nothing but your Activity class's Context
{
ArrayList<ContactEntity> allContacts = new ArrayList<>();
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Integer contactsCount = cursor.getCount(); // get how many contacts you have in your contacts list
if (contactsCount > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//the below cursor will give you details for multiple contacts
Cursor pCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
// continue till this cursor reaches to all phone numbers which are associated with a contact in the contact list
while (pCursor.moveToNext()) {
int phoneType = pCursor.getInt(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
//String isStarred = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
String phoneNo = pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//you will get all phone numbers according to it's type as below switch case.
ContactEntity entity = new ContactEntity();
entity.setName(contactName);
entity.setNumber(phoneNo);
allContacts.add(entity);
//Log.e will print all contacts according to contact types. Here you go.
switch (phoneType) {
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
Log.e(contactName + ": TYPE_MOBILE", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
Log.e(contactName + ": TYPE_HOME", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
Log.e(contactName + ": TYPE_WORK", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE:
Log.e(contactName + ": TYPE_WORK_MOBILE", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER:
Log.e(contactName + ": TYPE_OTHER", " " + phoneNo);
break;
default:
break;
}
}
pCursor.close();
}
}
cursor.close();
}
return allContacts;
}

I don't know what is your problem, but I have a code for getting phone number you can have a try:
public String getPhone(Context context, String contactID) {
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// Query and loop for every phone number of the contact
Cursor phoneCursor = context.getContentResolver().query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contactID}, null);
String phoneNo = "";
if(phoneCursor != null) {
while (phoneCursor.moveToNext()) {
phoneNo = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
}
phoneCursor.close();
}
return phoneNo;
}

Related

Deleting file that find using uri don't work

I want to build a File Manager.I get list of all files using ContentResolver.For example I get all audio file in this way:
private void getMusic(){
ContentResolver contentResolver=getContentResolver();
Uri songUri= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor songCursor=contentResolver.query(songUri,null,null,null,null);
if(songCursor!=null && songCursor.moveToFirst()){
Log.e(TAG,"if :");
int songTitle=songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int songPath=songCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
do{
String currentTitle=songCursor.getString(songTitle);
Uri currentPath=Uri.parse(songCursor.getString(songPath));
models.add(new model(currentTitle,currentPath));
adapter.notifyDataSetChanged();
}while (songCursor.moveToNext());
}
}
I write this method for deleting file, but didn't work for me.I also get WRITE and READ external permission from user.
private void deleteItem(int position){
File fdelete = new File(models.get(position).getPath().toString());
if (fdelete.exists()) {
boolean flag=fdelete.delete();
if (flag) {
models.remove(models.get(position));
adapter.notifyDataSetChanged();
disableSelectionMode();
Toast.makeText(this,"File successfully deleted.",Toast.LENGTH_SHORT).show();
} else {
disableSelectionMode();
Toast.makeText(this,"File did not deleted!",Toast.LENGTH_SHORT).show();
}
}
}
And this is my model:
public class model {
private int id;
private String title;
private Uri path;
public model(String title, Uri path) {
this.title = title;
this.path = path;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Uri getPath() {
return path;
}
public void setPath(Uri path) {
this.path = path;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Finally I find the solution.I should deleted file using ContentResolver. I done it this way:
private void deleteItem(model item){
switch (type){
case AUDIOS:{
int b=getContentResolver().delete(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
MediaStore.MediaColumns.DATA + "='" + item.getPath().getPath() + "'", null
);
Log.e(TAG,"b: "+b);
break;
}
case IMAGES:{
int b=getContentResolver().delete(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.MediaColumns.DATA + "='" + item.getPath().getPath() + "'", null
);
Log.e(TAG,"b: "+b);
break;
}
case VIDEOS:{
int b=getContentResolver().delete(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
MediaStore.MediaColumns.DATA + "='" + item.getPath().getPath() + "'", null
);
Log.e(TAG,"b: "+b);
break;
}
case COMPRESSED:
case APPS:
case DOCUMENTS :{
int bex=getContentResolver().delete(
MediaStore.Files.getContentUri("external"),
MediaStore.MediaColumns.DATA + "='" + item.getPath().getPath() + "'", null
);
int bin=getContentResolver().delete(
MediaStore.Files.getContentUri("internal"),
MediaStore.MediaColumns.DATA + "='" + item.getPath().getPath() + "'", null
);
Log.e(TAG,"bex: "+bex);
Log.e(TAG,"bin: "+bin);
break;
}
}
}

how to read the Contact faster? [duplicate]

This question already has an answer here:
Reading all contact data
(1 answer)
Closed 5 years ago.
I try to make Contact App and now I try to read the Contacts
I have 450 contacts and its take something like 60 sec to read them all.
I do it with Contact class:
public class Contact {
String name;
public ArrayList<String> PhoneNumber = new ArrayList<>();
public ArrayList<String> Email = new ArrayList<>();
int NumberOfPhones = 0;
int NumberOfMails = 0 ;
}
and I read like this :
tatic final int CODE_FOR_PERMISSION = 123;
List<Contact> ListContact = new ArrayList<Contact>();
Contact TempContact;
String TempName ="";
ArrayList<String> TempPhoneNumber = new ArrayList<>();
public ArrayList<String> TempEmail = new ArrayList<>();
int TempCounter = 0;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_activity);
AskForPermission();
pDialog = new ProgressDialog(this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
updateBarHandler = new Handler();
// Since reading contacts takes more time, let's run it on a separate thread.
new Thread(new Runnable() {
#Override
public void run() {
getContacts();
}
}).start();
//init();
//OnAction();
void init(){
textView = (TextView) findViewById(R.id.chekk);
}
void OnAction(){
TempContact.PrintToTextView(textView,ListContact);
}
public void getContacts() {
contactList = new ArrayList<String>();
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
TempName = name;
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
TempPhoneNumber.add(phoneNumber);
}
phoneCursor.close();
// Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
TempEmail.add(email);
output.append("\n Email:" + email);
}
emailCursor.close();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
Log.d("BDAY", birthdayCur.getCount()+"");
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
output.append("Birthday :" + birthday);
Log.d("BDAY", birthday);
}
}
birthdayCur.close();
}
// Add the contact to the ArrayList
contactList.add(output.toString());
TempContact = new Contact(TempName,TempPhoneNumber,TempEmail);
ListContact.add(TempContact);
TempName = "";
TempPhoneNumber.clear();
TempEmail.clear();
}
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 5);
}
}
how I can make the reading from contacts faster?
I have searched in other sutes but I don't know how to do it faster.
it can be done because the default contact app in the phone makes it very fast.
You don't need to query for all contacts + all emails + all phones to display the main contacts list similar to the default contacts app.
You'd probably notice that the main screen of all contacts apps display only names + picture, and not emails or phones.
Just perform the first query in your code to display the list of contacts, and only when the user clicks on one of those contacts, you'll open a new activity with the details of that specific contact only (which is a short query to make)

Couldn't read row 0, col -1 from CursorWindow Displaying Records

Good day, I was trying to retrieved my data's and display them in a simple way.
Here's my sample code: SQLiteLocalDatabase .java
public class SQLiteLocalDatabase extends SQLiteOpenHelper{
private SQLiteDatabase sqLiteDatabase;
private static final String DB_NAME = "project.db";
private static final int VERSION = 1;
public static final String DB_TABLE = " user ";
public static final String ID = " _id ";
public static final String FULL_NAME = " fullname ";
public static final String LOCATION = " location ";
public static final String EMAIL_ADD = " email ";
public static final String PASSWORD = " password ";
public SQLiteLocalDatabase(Context context) {
super(context, DB_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String queryTable = " CREATE TABLE " + DB_TABLE + "( " + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+ FULL_NAME + " TEXT , " + LOCATION + " TEXT NOT NULL, " + EMAIL_ADD + " TEXT , " + PASSWORD + " TEXT " + " ) ";
//setUpDb();
db.execSQL(queryTable);
}
public void setUpDb(){
//TO OPEN DATABASE - RE-WRITABLE
sqLiteDatabase = getWritableDatabase();
}
public void closeTransactionDb(){
//CLOSE DB IF OPEN
if(sqLiteDatabase != null && sqLiteDatabase.isOpen()){
sqLiteDatabase.close();
}
}
//INSERT DATA
public long insert(int id,String fullname, String location,String email,String password){
//CONTENT VALUE contains name-value-pairs
ContentValues values = new ContentValues();
if(id != -1) {
values.put(ID,id);
values.put(FULL_NAME, fullname);
values.put(LOCATION, location);
values.put(EMAIL_ADD, email);
values.put(PASSWORD, password);
}
//Object Table, column, values
return sqLiteDatabase.insert(DB_TABLE, null, values);
}
//UPDATE
public long update(int id, String fullname,String location,String email, String password){
//CONTENT VALUE contains name-value-pairs
ContentValues values = new ContentValues();
values.put(FULL_NAME,fullname);
values.put(LOCATION,location);
values.put(EMAIL_ADD,email);
values.put(PASSWORD,password);
//WHERE
String where = ID + " = " +id;
//Object Table, values, destination-id
return sqLiteDatabase.update(DB_TABLE, values, where, null);
}
//DELETE
//
public long delete(int id){
//WHERE
String where = ID + " = " +id;
//Object Table, values, destination-id
return sqLiteDatabase.delete(DB_TABLE, where, null);
}
public Cursor getAllRecords(){
String queryDB = "SELECT * FROM " + DB_TABLE;
return sqLiteDatabase.rawQuery(queryDB, null);
}
public Cursor getSingleRecord(){
String querySingleRecord = "SELECT * FROM " + DB_TABLE + "WHERE _id = " +ID;
return sqLiteDatabase.rawQuery(querySingleRecord,null);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
For my main: AddItemsActivity .java
public class AddItemsActivity extends AppCompatActivity implements View.OnClickListener{
SQLiteLocalDatabase sqLiteLocalDatabase;
TextView textViewDbData;
EditText editTextFullName;
EditText editTextAddress;
EditText editTextEmailAdd;
EditText editTextPassword;
EditText editTextIDNO;
Button btnSave;
Button btnUpdate;
Button btnSearch;
Button btnDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_items);
sqLiteLocalDatabase = new SQLiteLocalDatabase(AddItemsActivity.this);
//CALL FUNCTION
setUpWidgets();
}
public void setUpWidgets(){
textViewDbData = (TextView) findViewById(R.id.textViewDbData);
editTextFullName = (EditText) findViewById(R.id.editTextViewAddFullName);
editTextAddress = (EditText) findViewById(R.id.editTextAddLocation);
editTextEmailAdd = (EditText) findViewById(R.id.editTextAddEmailAddress);
editTextPassword = (EditText) findViewById(R.id.editTextRegPassword);
editTextIDNO = (EditText) findViewById(R.id.editTextAddID);
btnSave = (Button) findViewById(R.id.buttonAddContacts);
btnSave.setOnClickListener(this);
btnUpdate = (Button) findViewById(R.id.buttonUpdate);
btnUpdate.setOnClickListener(this);
btnSearch = (Button) findViewById(R.id.buttonDeleteRecord);
btnSearch.setOnClickListener(this);
btnDelete = (Button) findViewById(R.id.buttonShowRecords);
btnDelete.setOnClickListener(this);
}
public void clearTextFields(){
editTextFullName.setText("");
editTextAddress.setText("");
editTextEmailAdd.setText("");
editTextPassword.setText("");
editTextIDNO.setText("");
}
#Override
public void onClick(View v) {
String fullName = editTextFullName.getText().toString().trim();
String location = editTextAddress.getText().toString().trim();
String emailAdd = editTextEmailAdd.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
switch (v.getId()){
case R.id.buttonAddContacts:
//IF result == -1
long result = sqLiteLocalDatabase.insert(Integer.parseInt(getValue(editTextIDNO)), fullName, location, emailAdd, password);
if(result == -1){
Toast.makeText(AddItemsActivity.this, "Error: Someone own that Id",Toast.LENGTH_LONG).show();
}else
{
Toast.makeText(AddItemsActivity.this, "Success Id: " +result,Toast.LENGTH_LONG).show();
clearTextFields();
}
break;
case R.id.buttonUpdate:
if(editTextIDNO.getText().equals("")){
Toast.makeText(AddItemsActivity.this, "Please Enter User ID ",Toast.LENGTH_LONG).show();
}
else {
long update = sqLiteLocalDatabase.update(Integer.parseInt(getValue(editTextIDNO)),
getValue(editTextFullName),
getValue(editTextAddress),
getValue(editTextEmailAdd),
getValue(editTextPassword)
);
if (update == 0) {
Toast.makeText(AddItemsActivity.this, "Error Updating ", Toast.LENGTH_LONG).show();
} else if (update == -1) {
Toast.makeText(AddItemsActivity.this, "Successfully Modified", Toast.LENGTH_LONG).show();
clearTextFields();
} else {
Toast.makeText(AddItemsActivity.this, "Error All data updated Id: " + update, Toast.LENGTH_LONG).show();
}
}
break;
case R.id.buttonDeleteRecord:
long delete = sqLiteLocalDatabase.delete(Integer.parseInt(getValue(editTextIDNO)));
if(delete == 0) {
Toast.makeText(AddItemsActivity.this, "Error Delete", Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(AddItemsActivity.this, "Success Delete", Toast.LENGTH_LONG).show();
clearTextFields();
}
break;
case R.id.buttonShowRecords:
StringBuffer finalData = new StringBuffer();
Cursor cursor = sqLiteLocalDatabase.getAllRecords();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext() ){
finalData.append(cursor.getLong(cursor.getColumnIndex(sqLiteLocalDatabase.ID)));
finalData.append(" - ");
finalData.append(cursor.getString(cursor.getColumnIndex(sqLiteLocalDatabase.FULL_NAME)));
finalData.append(" - ");
finalData.append(cursor.getString(cursor.getColumnIndex(sqLiteLocalDatabase.LOCATION)));
finalData.append(" - ");
finalData.append(cursor.getInt(cursor.getColumnIndex(sqLiteLocalDatabase.EMAIL_ADD)));
finalData.append(" - ");
finalData.append(cursor.getInt(cursor.getColumnIndex(sqLiteLocalDatabase.PASSWORD)));
finalData.append("\n");
}
textViewDbData.setText(finalData);
break;
}
}
public String getValue(EditText editText){
return editText.getText().toString().trim();
}
#Override
protected void onStart() {
super.onStart();
sqLiteLocalDatabase.setUpDb();
}
#Override
protected void onStop() {
super.onStop();
sqLiteLocalDatabase.closeTransactionDb();
}
My problem was with the getAllRecords in the append part.
Logcat:
This is because one of the method of getting column index like cursor.getColumnIndex(sqLiteLocalDatabase.ID) returns -1.
Make sure the Cursor contains all the columns you are retrieving and check if getColumnIndex method is not returning -1.
if(cursor.getColumnIndex(sqLiteLocalDatabase.ID) != -1) {
finalData.append(cursor.getLong(cursor.getColumnIndex(sqLiteLocalDatabase.ID)));
finalData.append(" - ");
}
Likewise check all conditions.
Hope it'll work.

android.content.res.Resources$NotFoundException: Resource ID #0x88a6fd

I'm beginner and I'm trying to to load contact from database by clicking a button in a fragment, and then save outgoing call also in database?
ContactsFragemt.java
public class ContactsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>
{
SimpleCursorAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.contact, container, false);
final Button Button = (Button) view.findViewById(R.id.load_button);
final SQLDataBaseAdapter sqlDataBaseHelper = new SQLDataBaseAdapter(getActivity());
//*************************** method for population main contacts listView *********************************//
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String image_uri = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
int position = 0;
int exist = 0;
boolean imageComp, nameComp;
String[] contactsData = sqlDataBaseHelper.getContacts(position);
while (exist == 0 && (contactsData[0] != (null) || contactsData[1] != (null) || contactsData[2] != (null))) // we are checking that if it is reached at the end or not
{
if (contactsData[1] != null) {
if (contactsData[1].equals(phNumber)) // will make update if we got matched with phone number and if any of ther other parameter is changed
{
if (contactsData[2] == null) {
// pic is null saved in data base and
if (image_uri != null) {
sqlDataBaseHelper.updateTable1(null, null, null, null, contactsData[2], image_uri);
// then update new pic here
}
} else // but if their is pic
if (!contactsData[2].equals(image_uri)) { // and he/she update pic with a brand new picture then
sqlDataBaseHelper.updateTable1(null, null, null, null, contactsData[2], image_uri);
}
if (contactsData[0] == null) {
// name is null saved in data base and
if (contactName != null) {
sqlDataBaseHelper.updateTable1(contactsData[0], contactName, null, null, null, null);
// then update new name here
}
} else // if name was saved previously in based
if (!contactsData[0].equals(contactName)) { //but the guy changed his name so
sqlDataBaseHelper.updateTable1(contactsData[0], contactName, null, null, null, null);
}
exist = 1;
}
}
position++;
contactsData = sqlDataBaseHelper.getContacts(position);
}
if (exist == 0) // means if number is not in the list then make update
{
long id = sqlDataBaseHelper.insertData1(contactName, phNumber, image_uri);
if (id < 0) {
Toast.makeText(getActivity(), "Data1 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Data1 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
}
String[] fromFieldNames = sqlDataBaseHelper.fromFieldName1();
int[] toViewIDs = sqlDataBaseHelper.toIds1();
adapter = new SimpleCursorAdapter(getActivity(),
R.layout.list_items_view,
null,
fromFieldNames,
toViewIDs,0);
ListView mainList = (ListView) view.findViewById(R.id.main_list_view);
mainList.setAdapter(adapter);
getLoaderManager().initLoader(0, null, ContactsFragment.this);
}
});
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = ContentProvider.CONTENT_URI;
return new CursorLoader(getActivity(), uri, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader loader) {
adapter.swapCursor(null);
}
}
SimpleCursorAdapter.java
public class SimpleCursorAdapter extends android.widget.SimpleCursorAdapter {
Context mcontext;
String[] values;
Cursor cursor;
int[] to;
public SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.values = from;
this.to = to;
this.cursor = c;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(list_items_view, parent, false);
final ImageButton call = (ImageButton) view.findViewById(R.id.call);
ImageButton sms = (ImageButton) view.findViewById(R.id.sms);
final TextView contact_no = (TextView) view.findViewById(R.id.contact_no);
final TextView contactName = (TextView) view.findViewById(R.id.contact_name);
ImageView contactImage = (ImageView) view.findViewById(R.id.contact_image);
final SQLDataBaseAdapter sqlDataBaseHelper = new SQLDataBaseAdapter(mcontext);
//********************************** method for calling from app****************************/
call.setOnClickListener(new View.OnClickListener() { //when phone button is clicked
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(String.valueOf("tel:" + contact_no.getText().toString())));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//*/
if (ActivityCompat.checkSelfPermission(mcontext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mcontext.startActivity(callIntent);//*/
Calendar rightNow = Calendar.getInstance();
int hourOfDay = rightNow.get(Calendar.HOUR_OF_DAY);
String AM_PM;
if (hourOfDay > 12) { // for 12 hours format
hourOfDay = hourOfDay - 12;
AM_PM = "PM";
} else {
AM_PM = "AM";
}
String time = Integer.toString(hourOfDay)
+ " : " + Integer.toString(rightNow.get(Calendar.MINUTE))
+ " " + AM_PM;
String date = Integer.toString(rightNow.get(Calendar.DAY_OF_MONTH))
+ "/" + Integer.toString(rightNow.get(Calendar.MONTH) + 1)
+ "/" + Integer.toString(rightNow.get(Calendar.YEAR));
String name = contactName.getText().toString();
Cursor c = mcontext.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
if (c.moveToNext() == true) {
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));
String pic = Uri.parse("android.resource://com.example.asim.simpleviewpager/drawable/outgoing_call.png").toString();
long id = sqlDataBaseHelper.insertData2(name, duration, pic, time, date);
if (id < 0) {
Toast.makeText(mcontext, "Data2 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mcontext, "Data2 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
c.close();
}
});
//********************************** method for sending message from app****************************//
sms.setOnClickListener(new View.OnClickListener() { //when sms button is clicked
#Override
public void onClick(View v) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + contact_no.getText().toString()));
smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mcontext.startActivity(smsIntent);
Calendar rightNow = Calendar.getInstance();
int hourOfDay = rightNow.get(Calendar.HOUR_OF_DAY);
String AM_PM;
if (hourOfDay > 12) {
hourOfDay = hourOfDay - 12;
AM_PM = "PM";
} else {
AM_PM = "AM";
}
String time = Integer.toString(hourOfDay)
+ " : " + Integer.toString(rightNow.get(Calendar.MINUTE))
+ " " + AM_PM;
String date = Integer.toString(rightNow.get(Calendar.DAY_OF_MONTH))
+ "/" + Integer.toString(rightNow.get(Calendar.MONTH) + 1)
+ "/" + Integer.toString(rightNow.get(Calendar.YEAR));
String name = contactName.getText().toString();
String duration = "000 000 000";
String pic = Uri.parse("android.resource://com.example.asim.simpleviewpager/drawable/message_sent.png").toString();
long id = sqlDataBaseHelper.insertData2(name, duration, pic, time, date);
if (id < 0) {
Toast.makeText(mcontext, "Data2 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mcontext, "Data2 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
});
//************************** Reading contact from SQLDataBase for each item*************************************//
String[] contactsData = sqlDataBaseHelper.getContacts(position);
if (contactsData[0] != (null)) {
contactName.setText(contactsData[0]);
contact_no.setText(contactsData[1]);
if (contactsData[2] == (null)) {
contactImage.setImageResource(R.drawable.w4j8n);
} else {
contactImage.setImageURI(Uri.parse(contactsData[2]));
}
}//*/
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
}
}
ContentProvider.java
public class ContentProvider extends android.content.ContentProvider {
public static final String PROVIDER_NAME = "com.example.asim.simpleviewpager"; //.contentprovider
public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/ContactsDataBase");
private static final int CONTENTPROVIDERS = 1;
private static final UriMatcher uriMatcher ;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "ContactsDataBase", CONTENTPROVIDERS);
}
SQLDataBaseAdapter sqlDataBaseAdapter;
#Override
public boolean onCreate() {
sqlDataBaseAdapter = new SQLDataBaseAdapter(getContext());
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
if (uriMatcher.match(uri) == CONTENTPROVIDERS) {
return sqlDataBaseAdapter.getAllContacts();
} else {
return null;
}
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
SQLDataBaseAdapter.java
public class SQLDataBaseAdapter {
SQLDataBaseHelper sqlDataBaseHelper;
public SQLDataBaseAdapter(Context context){
sqlDataBaseHelper = new SQLDataBaseHelper(context);
}
public long insertData1(String contactName, String contactNo, String pic){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, contactName);
contentValues.put(SQLDataBaseHelper.NO, contactNo);
contentValues.put(SQLDataBaseHelper.PICTURE, pic);
long id = db.insert(SQLDataBaseHelper.TABLE1_NAME,null,contentValues);
return id;
}
public long insertData2(String contactName, String duration, String time, String date, String pic ){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, contactName);
contentValues.put(SQLDataBaseHelper.DURATION, duration);
contentValues.put(SQLDataBaseHelper.TIME, time);
contentValues.put(SQLDataBaseHelper.DATE, date);
contentValues.put(SQLDataBaseHelper.PICTURE, pic);
long id = db.insert(SQLDataBaseHelper.TABLE2_NAME,null,contentValues);
return id;
}
public String[] getContacts(int position) {
String[] contactsData = new String[3];
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
String[] columns = {SQLDataBaseHelper.UID, SQLDataBaseHelper.NAME, SQLDataBaseHelper.PICTURE, SQLDataBaseHelper.NO};
Cursor cursor = db.query(SQLDataBaseHelper.TABLE1_NAME, columns, null, null, null, null, null);
cursor.moveToPosition(position);
int pos = cursor.getPosition();
int cnt = cursor.getCount();
int checkElement = cnt-pos;
if (checkElement > 0)
{
cursor.moveToPosition(position);
int nameColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.NAME);
String name = cursor.getString(nameColumnIndex);
int noColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.NO);
String contactNo = cursor.getString(noColumnIndex);
int picColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.PICTURE);
String picture = cursor.getString(picColumnIndex);
contactsData[0] = name;
contactsData[1] = contactNo;
contactsData[2] = picture;
} else
{
contactsData[0] = null;
contactsData[1] = null;
contactsData[2] = null;
}
cursor.close();
db.close();
return contactsData;
}
public void updateTable1 (String oldName, String newName, String oldPhoneNo, String NewPhoneNumber, String oldPic, String newPic) {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
if (oldName != newName) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, newName);
String[] whereArgs = {oldName};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.NAME+" =? ",whereArgs);
}
if(oldPhoneNo!=NewPhoneNumber){
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NO, NewPhoneNumber);
String[] whereArgs = {oldPhoneNo};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.NO+" =? ",whereArgs);
}
if(oldPic!=newPic){
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.PICTURE, NewPhoneNumber);
String[] whereArgs = {oldPic};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.PICTURE+" =? ",whereArgs);
}
}
public void deleteRowTable1()
{
}
public void updateTable2 ()
{
}
public void deleteRowTable2()
{
}
/////////////////////////////////////////////////////////////////////
public Cursor getAllContacts(){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
return db.query(SQLDataBaseHelper.TABLE1_NAME, new String[] {
SQLDataBaseHelper.UID,SQLDataBaseHelper.NAME, SQLDataBaseHelper.NO, SQLDataBaseHelper.PICTURE},
null, null, null, null,
SQLDataBaseHelper.NAME + " asc ");
}
public SQLDataBaseAdapter open() {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
return this;
}
public Cursor getAllRows1() {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
Cursor cursor = db.query(true, SQLDataBaseHelper.TABLE1_NAME, SQLDataBaseHelper.ALL_KEYS1, null, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public String[] fromFieldName1(){///
String[] fields = new String[] {SQLDataBaseHelper.UID,SQLDataBaseHelper.NAME, SQLDataBaseHelper.NO, SQLDataBaseHelper.PICTURE};
return fields;
}
public int[] toIds1(){
int[] toViewIds = new int[]{R.id.contact_name,R.id.contact_no,R.id.contact_image};
return toViewIds;
}
static class SQLDataBaseHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "ContactsDataBase";
private static final String TABLE1_NAME = "CALLS_TABLE1";
private static final String TABLE2_NAME = "LOGS_TABLE";
private static final int DATABASE_VERSION = 1;
private static final String UID = "_id";
private static final String NAME = "Name";
private static final String NO = "ContactNo";
private static final String DURATION = "Duration";
private static final String PICTURE = "Picture";
private static final String DATE = "Date";
private static final String TIME = "Time";
private static final String[] ALL_KEYS1 = new String[] {UID,NAME, NO, PICTURE};
private static final String CREATE_TABLE1 = "CREATE TABLE "+TABLE1_NAME+" (" +UID+
" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+NO+" VARCHAR(255), "
+PICTURE+" VARCHAR(255));";
private static final String CREATE_TABLE2 = "CREATE TABLE "+TABLE2_NAME+" ("
+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+DURATION+" VARCHAR(255), "
+PICTURE+" VARCHAR(255), " +DATE+ " VARCHAR(255), "+TIME+ " VARCHAR(255));";
private static final String DROP_TABLE1 = "DROP TABLE IF EXIST"+ TABLE1_NAME ;
private static final String DROP_TABLE2 = "DROP TABLE IF EXIST"+ TABLE2_NAME ;
private Context context;
public SQLDataBaseHelper (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE1);
Toast.makeText(context,"onCreate1 called" , Toast.LENGTH_SHORT).show();
} catch (SQLException e) {
Toast.makeText(context,""+e , Toast.LENGTH_SHORT).show();
Log.e("exception in onCreate", "here is exception " + e);
} //*/
try {
db.execSQL(CREATE_TABLE2);
Toast.makeText(context,"onCreate2 called" , Toast.LENGTH_SHORT).show();
} catch (SQLException e) {
Toast.makeText(context,""+e , Toast.LENGTH_SHORT).show();
Log.e("exception in onCreate", "here is exception " + e);
} //*/
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE1);
Toast.makeText(context,"onUpgrade1 called" , Toast.LENGTH_SHORT).show();
onCreate(db);
}catch (SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_SHORT).show();
}
try {
db.execSQL(DROP_TABLE2);
Toast.makeText(context,"onUpgrade2 called" , Toast.LENGTH_SHORT).show();
onCreate(db);
}catch (SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_SHORT).show();
}
}
}
}
and these are the errors
01-30 04:03:23.804 2702-2702/com.example.asim.simpleviewpager E/AndroidRuntime: FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: Resource ID #0x88a6fd
at android.content.res.Resources.getValue(Resources.java:1049)
at android.content.res.Resources.getDrawable(Resources.java:664)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:323)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:175)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:168)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:51)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:72)
at android.support.v4.widget.SimpleCursorAdapter.setViewImage(SimpleCursorAdapter.java:195)
at android.support.v4.widget.SimpleCursorAdapter.bindView(SimpleCursorAdapter.java:143)
In SimpleCursorAdapter.java, you have a method bindView() which overrides the same method from its parent class, but you don't put any code in that method. Deleting the method should fix the error. But if you plan to override how binding works in that method, you may want to put some code in there starting with something like
super.bindView(view, context, cursor);

How to keep count of the times an existing record being inserted in database?

I am totally new in this and I am sure I screwed the code somehow, please help me fix it.
I have the following contentprovider for building a database to store favourite tags:
public class FTagsContentProvider extends ContentProvider {
static final String AUTHORITY = "ch.ethz.twimight.FTags";
private static final String BASE_PATH = "ftags";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH);
// fields for the database
public static final String COL_ID = "id";
public static final String COL_TEXT = "text";
public static final String COL_COUNT = "count";
static final int FTAGS = 1;
static final int FTAGS_ID = 2;
DBHelper dbHelper;
private static HashMap<String, String> FTagsMap;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, BASE_PATH, FTAGS);
uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", FTAGS_ID);
}
// database declarations
private SQLiteDatabase database;
static final String DATABASE_NAME = "ftagtable.db";
static final String TABLE_FTAGS = "FTags";
static final int DATABASE_VERSION = 1;
private static final String TABLE_FTAGS_CREATE = "create table "
+ TABLE_FTAGS
+ "("
+ COL_ID + " integer primary key autoincrement, "
+ COL_TEXT + " text not null, "
+ COL_COUNT + " integer"
+ ");";
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(TABLE_FTAGS_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(DBHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ". Old data will be destroyed");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FTAGS);
onCreate(db);
}
}
#Override
public boolean onCreate() {
// TODO Auto-generated method stub
Context context = getContext();
dbHelper = new DBHelper(context);
database = dbHelper.getWritableDatabase();
if(database == null)
return false;
else
return true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_FTAGS);
switch (uriMatcher.match(uri)) {
case FTAGS:
queryBuilder.setProjectionMap(FTagsMap);
break;
case FTAGS_ID:
queryBuilder.appendWhere( COL_ID + "=" + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == ""){
sortOrder = COL_TEXT;
}
Cursor cursor = queryBuilder.query(database, projection, selection,
selectionArgs, null, null, sortOrder);
/**
* register to watch a content URI for changes
*/
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
long row = database.insert(TABLE_FTAGS, "", values);
if(row > 0) {
Uri newUri = ContentUris.withAppendedId(CONTENT_URI, row);
getContext().getContentResolver().notifyChange(newUri, null);
return newUri;
}
throw new SQLException("Fail to add a new record into " + uri);
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
int rowsUpdated = 0;
switch (uriMatcher.match(uri)){
case FTAGS:
rowsUpdated = database.update(TABLE_FTAGS, values, selection, selectionArgs);
break;
case FTAGS_ID:
rowsUpdated = database.update(TABLE_FTAGS, values, COL_ID +
" = " + uri.getLastPathSegment() +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI " + uri );
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
int count = 0;
switch (uriMatcher.match(uri)){
case FTAGS:
count = database.delete(TABLE_FTAGS, selection, selectionArgs);
break;
case FTAGS_ID:
String id = uri.getLastPathSegment(); //gets the id
count = database.delete( TABLE_FTAGS, COL_ID + " = " + id +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
#Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}
I want to set the COL_COUNT as a value of keeping count the times that a tag has been inserted into the database, originally it should be 1 for each tag, and I want it to update only the count like from 1 to 2 and so on every time an existing tag is input.
Here is the Activity:
public class TestActivity extends Activity {
private EditText mText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
}
public boolean check(String s){
boolean t = false;
ContentResolver contentResolver = this.getContentResolver();
Cursor cursor = contentResolver.query(FTagsContentProvider.CONTENT_URI,
new String []{FTagsContentProvider.COL_TEXT}, FTagsContentProvider.COL_TEXT + "=?", new String[]{s}, null);
if(cursor.getCount > 0){
t = true;
}
else{
t = false;
}
cursor.close();
return t;
}
public void addFTag(View view) {
// Add a new tag
ContentValues values = new ContentValues();
mText = (EditText)findViewById(R.id.name);
String mFtag = mText.getText().toString();
boolean exist = check(mFtag);
if(exist == false){
values.put(FTagsContentProvider.COL_TEXT,
mFtag);
Uri uri = getContentResolver().insert(
FTagsContentProvider.CONTENT_URI, values);
Toast.makeText(getBaseContext(),
"Record inserted!", Toast.LENGTH_LONG).show();
}
else{
// code for only updating the COL_COUNT somehow
Toast.makeText(this, "Some tag meet you again :)",
Toast.LENGTH_LONG).show();
}}
public void showAllTags(View view) {
Cursor c = getContentResolver().query(FTagsContentProvider.CONTENT_URI, null, null, null, null);
String result = "Results:";
if (!c.moveToFirst()) {
Toast.makeText(this, result+" no content yet!", Toast.LENGTH_LONG).show();
}else{
do{
result = result + "\n" + c.getString(c.getColumnIndex(FTagsContentProvider.COL_TEXT)) +
" with id " + c.getString(c.getColumnIndex(FTagsContentProvider.COL_ID)) +
" has count: " + c.getString(c.getColumnIndex(FTagsContentProvider.COL_COUNT));
} while (c.moveToNext());
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
}
}
Any help would be much appreciated :)

Categories