Invalid column data1 error while retrieving contact number using Loader - android

public class MainActivity extends BaseActivity implements View.OnClickListener, LoaderManager.LoaderCallbacks<Cursor>{
private static final String TAG = "ContentProviderDemo";
private int recentOpPerfomed;
private final int LOAD_CONTACTS=1;
private final int WRITE_CONTACTS=2;
private final int UPDATE_CONTACTS=3;
private final int DELETE_CONTACTS=4;
private boolean firstTimeLoaded=false;
private TextView textViewQueryResult;
private Button buttonLoadData, buttonAddContact,buttonRemoveContact,buttonUpdateContact, buttonPhotoTagActivity;
private ContentResolver contentResolver;
private EditText editTextContactName;
private CursorLoader mContactsLoader;
private String[] mColumnProjection = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.CommonDataKinds.Phone.NUMBER}
;
private String mSelectionCluse = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " = ?";
private String[] mSelectionArguments = new String[]{"Ajay"};
private String mOrderBy = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewQueryResult = (TextView) findViewById(R.id.textViewQueryResult);
editTextContactName=(EditText)findViewById(R.id.editTextContactName);
buttonLoadData = (Button) findViewById(R.id.buttonLoadData);
buttonAddContact=(Button)findViewById(R.id.buttonAddContact);
buttonRemoveContact=(Button)findViewById(R.id.buttonRemoveContact);
buttonUpdateContact=(Button)findViewById(R.id.buttonUpdateContact);
buttonPhotoTagActivity=(Button)findViewById(R.id.buttonPhotoTagActivity);
buttonLoadData.setOnClickListener(this);
buttonAddContact.setOnClickListener(this);
buttonRemoveContact.setOnClickListener(this);
buttonUpdateContact.setOnClickListener(this);
buttonPhotoTagActivity.setOnClickListener(this);
contentResolver=getContentResolver();
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
if(i==1){
return new CursorLoader(this,ContactsContract.Contacts.CONTENT_URI,mColumnProjection, null,null,null);
}
return null;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if(cursor!=null && cursor.getCount()>0){
StringBuilder stringBuilderQueryResult=new StringBuilder("");
while (cursor.moveToNext()){
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
// Query phone here. Covered next
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "
+ ContactsContract.Contacts._ID, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("Number", phoneNumber);
stringBuilderQueryResult.append(cursor.getString(0)+" , "+cursor.getString(1)+
" , "+cursor.getString(2)+" , "+phoneNumber+"\n");
}
phones.close();
}
}
textViewQueryResult.setText(stringBuilderQueryResult.toString());
}else{
textViewQueryResult.setText("No Contacts in device");
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonLoadData:loadContacts();
break;
case R.id.buttonAddContact: addContact();
break;
case R.id.buttonRemoveContact:deleteContact();
break;
case R.id.buttonUpdateContact: modifyCotact();
break;
case R.id.buttonPhotoTagActivity: startPhotoTagActivity();
break;
default:
break;
}
}
private void startPhotoTagActivity(){
startActivity(new Intent(this,PhotoTaggingActivity.class));
}
private void insertContacts(){
String newName=editTextContactName.getText().toString();
if(newName!=null && !newName.equals("") && newName.length()!=0){
ArrayList<ContentProviderOperation> cops=new ArrayList<ContentProviderOperation>();
cops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE,"accountname#gmail.com")
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "com.google")
.build());
cops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, editTextContactName.getText().toString())
.build());
try{
getContentResolver().applyBatch(ContactsContract.AUTHORITY,cops);
}catch (Exception exception){
Log.i(TAG,exception.getMessage());
Toast.makeText(this,exception.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
private void addContact() {
recentOpPerfomed=WRITE_CONTACTS;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
insertContacts();
} else {
requestRunTimePermissions(this,new String[]{Manifest.permission.WRITE_CONTACTS},MY_PERMISSION_REQUEST_WRITE_CONTACTS);
}
}
private void updateContact(){
String [] updateValue=editTextContactName.getText().toString().split(" ");
ContentProviderResult[] result=null;
String targetString=null;
String newString=null;
if(updateValue.length==2){
targetString=updateValue[0];
newString=updateValue[1];
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
if(newString!=null && !newString.equals("") && newString.length()!=0)
{
String where= ContactsContract.RawContacts._ID + " = ? ";
String [] params= new String[] {targetString};
ContentResolver contentResolver=getContentResolver();
ContentValues contentValues=new ContentValues();
contentValues.put(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY,newString);
// UPDATE <table_name> SET column1 = value1, column2 = value2 where column3 = selection_value
contentResolver.update(ContactsContract.RawContacts.CONTENT_URI,contentValues, where,params);
}
}
}
}
private void modifyCotact(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
updateContact();
} else {
requestRunTimePermissions(this,new String[]{Manifest.permission.WRITE_CONTACTS}, MY_PERMISSION_REQUEST_WRITE_CONTACTS);
}
}
private void removeContacts(){
recentOpPerfomed=DELETE_CONTACTS;
String newName=editTextContactName.getText().toString();
if(newName!=null && !newName.equals("") && newName.length()!=0){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
//display_name = '<entered_value>'
String whereClause=ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY+ " = '"+editTextContactName.getText().toString()+"'";
//DELETE FROM <table_name> where column1 = selection_value
getContentResolver().delete(ContactsContract.RawContacts.CONTENT_URI,whereClause,null);
}
}
}
private void deleteContact(){
recentOpPerfomed=DELETE_CONTACTS;
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.WRITE_CONTACTS)==PackageManager.PERMISSION_GRANTED){
removeContacts();
}else{
requestRunTimePermissions(this,new String[]{Manifest.permission.WRITE_CONTACTS}, MY_PERMISSION_REQUEST_WRITE_CONTACTS);
}
}
private void loadContacts() {
recentOpPerfomed=LOAD_CONTACTS;
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.READ_CONTACTS)==PackageManager.PERMISSION_GRANTED){
Log.i(TAG,"Permisssion is granted");
if (firstTimeLoaded == false) {
getLoaderManager().initLoader(1, null, this);
firstTimeLoaded = true;
} else {
getLoaderManager().restartLoader(1, null, this);
}
}else{
requestRunTimePermissions(this,new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(permissions.length==1){
if(requestCode==MY_PERMISSIONS_REQUEST_READ_CONTACTS || requestCode==MY_PERMISSION_REQUEST_WRITE_CONTACTS && grantResults[0]==PackageManager.PERMISSION_GRANTED){
switch (recentOpPerfomed){
case WRITE_CONTACTS: addContact();loadContacts();break;
case DELETE_CONTACTS: deleteContact();loadContacts();break;
case UPDATE_CONTACTS: modifyCotact();loadContacts();break;
case LOAD_CONTACTS:loadContacts();
default: break;
}
}
}
}
}
Wasted almost an day on this. Trying to get Phone Number from Contacts APP.
I am trying to retrieve all contacts phone number using Loader. There is no proper explanation in Logcat where i am going wrong. Any help would be greatly appreciated. I keep getting saying Invalid column data1,but what is Invalid column data1?

Related

ClearCallLog not updating listview

I am a school student learning android. I am doing a simple contacts app! When i click on clear calllog button, my recent contacts listview remains the same. Its not getting cleared. But when i close the app and reopen again, the recent contacts fragment is getting cleared! I debugged the code, code is not entering after cursor.movetoNext() line when i click on clearcall log. Kindly help me techies!
I programmed like updateFragment2ListView() gets called when i clear the call log button in menu!
public class RecentContacts extends Fragment {
HashMap contactMap = new HashMap();
View rootView;
RecentAdapter rr;
ListView list;
private static final int PERMISSIONS_REQUEST_READ_CALLLOG = 100;
Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_recent_contacts, container, false);
list = (ListView) rootView.findViewById(R.id.customlist);
getRecentContacts();
rr = new RecentAdapter(contactMap, getActivity());
list.setAdapter(rr);
return rootView;
}
public void updateFragment2ListView() {
getRecentContacts();
rr.notifyDataSetChanged();
list.setAdapter(rr);
System.out.println("Fragment recent updated-updateFragment2listview");
}
#Override
public void onResume() {
getRecentContacts();
rr.notifyDataSetChanged();
System.out.println("Fragment recent updated- onresume");
super.onResume();
}
#Override
public void onStart() {
System.out.println("Fragment recent onstart");
super.onStart();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
void getRecentContacts() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && getContext().checkSelfPermission(Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CALL_LOG}, PERMISSIONS_REQUEST_READ_CALLLOG);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
System.out.println("Security check ok");
} else {
System.out.println("Entered recent onstart");
int i=0;
Uri queryUri = android.provider.CallLog.Calls.CONTENT_URI;
String[] projection = new String[]{
ContactsContract.Contacts._ID,
CallLog.Calls._ID,
CallLog.Calls.NUMBER,
CallLog.Calls.CACHED_NAME,
CallLog.Calls.DATE,
CallLog.Calls.TYPE};
String sortOrder = String.format("%s limit 500 ", CallLog.Calls.DATE + " DESC");
try {
System.out.println("Entering cursor in recent contacts");
cursor = getActivity().getContentResolver().query(queryUri, projection, null, null, sortOrder);
System.out.println("Entered cursor in recent contacts");
} catch (SecurityException e) {
Log.e("", "");
}
while (cursor.moveToNext()) {
System.out.println("Entered cursor.movetoNext recent contacts");
String phoneNumber = cursor.getString(cursor
.getColumnIndex(CallLog.Calls.NUMBER));
System.out.println("Entered phone number in recent contacts");
String title = (cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)));
int duration1 = cursor.getColumnIndex(CallLog.Calls.DURATION);
System.out.println("Duration" + duration1);
System.out.println("Entered duration in recent contacts");
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
System.out.println("Call Date" + callDayTime);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
String callType = cursor.getString(type);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
System.out.println("Call type" + dir);
// if (phoneNumber == null || title == null) continue;
String uri = "tel:" + phoneNumber;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
String intentUriString = intent.toUri(0);
contactMap.put(i, new RecentPojo(title, phoneNumber, duration1, false, callDayTime, dir));
// Toast.makeText(this,title,Toast.LENGTH_SHORT).show();
i++;
}
cursor.close();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if ((requestCode == PERMISSIONS_REQUEST_READ_CALLLOG)) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
System.out.println("");
getRecentContacts();
} else {
Toast.makeText(getContext(), "Until you grant the permission, we cannot display the names", Toast.LENGTH_SHORT).show();
}
}
}
}
You have to call rr.notifyDataSetChanged(); when you clear it so the ListView is refreshed.

Null pointer exception while uploading contacts to server

Here i am fetching the name,email,phone number from the mobile and trying to upload to server..Here if the contacts contains name,email and phone number the values will be inserted successfully..but if any of the field is empty it is throwing NULL pointer exception.How to avoid this one..i mean if the contact does not contain email it should atleast send name and phone number.
here is my code.
public class DisplayContact1 extends Activity {
private static String TAG = WorkDetails1.class.getSimpleName();
Button select;
private String vault;
List<AddressBookContact> list;
public static final String kvault = "vault_no";
public static final String kname = "name";
public static final String kphone = "phone";
public static final String kemail = "email";
public static final String kcontacts = "contacts";
public static final String SHARED_PREF_NAME = "myloginapp";
public static final String UPLOAD_URL = "http://oursite.com/contacts_1.php";
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
Cursor cursor;
LongSparseArray<AddressBookContact> array;
long start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.display);
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
getAllContacts(this.getContentResolver());
}
public void getAllContacts(ContentResolver cr) {
int result = ContextCompat.checkSelfPermission(DisplayContact1.this, Manifest.permission.READ_CONTACTS);
if (result == PackageManager.PERMISSION_GRANTED){
//fetches contacts from the phone contact list and displays in ascending order
list = new LinkedList<AddressBookContact>();
array = new LongSparseArray<AddressBookContact>();
start = System.currentTimeMillis();
String[] projection = {
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Contactables.DATA,
ContactsContract.CommonDataKinds.Contactables.TYPE,
};
String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";
String[] selectionArgs = {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
};
String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
Uri uri = ContactsContract.Data.CONTENT_URI;
// we could also use Uri uri = ContactsContract.Data.CONTENT_URI;
cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
contactsdisplay();
} else {
requestForLocationPermission();
}
}
private void requestForLocationPermission()
{
if (ActivityCompat.shouldShowRequestPermissionRationale(DisplayContact1.this, Manifest.permission.READ_CONTACTS))
{
}
else {
ActivityCompat.requestPermissions(DisplayContact1.this, new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getAllContacts(DisplayContact1.this.getContentResolver());
contactsdisplay();
}
break;
}
}
public void contactsdisplay() {
//Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);
while (cursor.moveToNext()) {
long id = cursor.getLong(idIdx);
AddressBookContact addressBookContact = array.get(id);
if (addressBookContact == null) {
addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), getResources());
array.put(id, addressBookContact);
list.add(addressBookContact);
}
int type = cursor.getInt(typeIdx);
String data = cursor.getString(dataIdx);
String mimeType = cursor.getString(mimeTypeIdx);
if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
// mimeType == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
addressBookContact.addEmail(type, data);
} else {
// mimeType == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
addressBookContact.addPhone(type, data);
}
}
long ms = System.currentTimeMillis() - start;
cursor.close();
// done!!! show the results...
int i = 1;
for (AddressBookContact addressBookContact : list) {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
}
final String cOn = "<b><font color='#ff9900'>";
final String cOff = "</font></b>";
Spanned l1 = Html.fromHtml("got " + cOn + array.size() + cOff + " contacts<br/>");
Spanned l2 = Html.fromHtml("query took " + cOn + ms / 1000f + cOff + " s (" + cOn + ms + cOff + " ms)");
Log.d(TAG, "\n\n╔══════ query execution stats ═══════" );
Log.d(TAG, "║ " + l1);
Log.d(TAG, "║ " + l2);
Log.d(TAG, "╚════════════════════════════════════" );
SpannableStringBuilder msg = new SpannableStringBuilder().append(l1).append(l2);
ListView lv= (ListView) findViewById(R.id.lv);
lv.setAdapter(new ArrayAdapter<AddressBookContact>(this, android.R.layout.simple_list_item_1, list));
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
uploadImage();
}
});
}
public void uploadImage(){
SharedPreferences sharedPreferences = getSharedPreferences(DisplayContact.SHARED_PREF_NAME, MODE_PRIVATE);
final String vault_no = vault;
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(DisplayContact1.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("Successfully Saved")){
//Intent intent = new Intent(CollegeDetails.this,Work.class);
Toast.makeText(DisplayContact1.this, s, Toast.LENGTH_SHORT).show();
// startActivity(intent);
}else{
Toast.makeText(DisplayContact1.this,s,Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
//RegisterUserClass rh = new RegisterUserClass();
HashMap<String,String> param = new HashMap<String,String>();
JSONArray contacts = new JSONArray();
int i = 1;
for (AddressBookContact addressBookContact : list) {
try {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
JSONObject contact = new JSONObject();
contact.put(kname, addressBookContact.name.toString());
contact.put(kvault, vault_no);
contact.put(kphone, addressBookContact.phone.toString());
if(addressBookContact.email.toString()!=null)
contact.put(kemail, addressBookContact.email.toString());
contacts.put(contact);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
param.put(kcontacts, contacts.toString());
System.out.println("param value.." + i++ +":"+ contacts.toString());
}
return rh.sendPostRequest(UPLOAD_URL, param);
}
}
UploadImage u = new UploadImage();
u.execute();
}
}
here is the AddressBookContact.class
public class AddressBookContact {
private long id;
private Resources res;
String name;
LongSparseArray<String> email;
LongSparseArray<String> phone;
AddressBookContact(long id, String name, Resources res) {
this.id = id;
this.name = name;
this.res = res;
}
#Override
public String toString() {
return toString(false);
}
public String toString(boolean rich) {
SpannableStringBuilder builder = new SpannableStringBuilder();
if (rich) {
builder.append("id: ").append(Long.toString(id))
.append(", name: ").append(name);
} else {
builder.append("name: ").append(name);
}
if (phone != null) {
builder.append("\nphone: ");
for (int i = 0; i < phone.size(); i++) {
int type = (int) phone.keyAt(i);
builder.append(phone.valueAt(i));
if (i + 1 < phone.size()) {
builder.append(", ");
}
}
}
if (email != null) {
builder.append("\nemail: ");
for (int i = 0; i < email.size(); i++) {
int type = (int) email.keyAt(i);
builder.append(email.valueAt(i));
if (i + 1 < email.size()) {
builder.append(", ");
}
}
}
return builder.toString();
}
public void addEmail(int type, String address) {
if (email == null) {
email = new LongSparseArray<String>();
}
email.put(type, address);
}
public void addPhone(int type, String number) {
if (phone == null) {
phone = new LongSparseArray<String>();
}
phone.put(type, number);
}
}
if email field is empty, i am getting null pointer exception at this line..
contact.put(kemail, addressBookContact.email.toString());..so i have added if loop to check the null condition..but then also i am getting exception.
Here
if (addressBookContact.email.toString() != null)
you try to get String from 'email' variable that is null.
Correct comparing is:
if (addressBookContact.email != null)
Add two conditions as below your string might not be null but can be
empty ""
if(addressBookContact.email.toString() != null && !addressBookContact.email.toString().equalsIgnoreCase(""))
contact.put(kemail, addressBookContact.email.toString());
Use TextUtils.
if(!TextUtils.isEmpty(addressBookContact.email.toString())){
contact.put(kemail, addressBookContact.email.toString());
}
And if kemail is compulsory field then in else condition just pass "" empty value.

How to update Recyclerview data from another activity

I have two activities MainActivity and Addlogactivity i am updating a data in Addlogactivity which should be displayed in mainactivity recyclerview the data is not updating in database
MianActivityClass :
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{
RecyclerView recyclerView;
Intent addDisplay;
Mainrow_Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.listView);
addDisplay = new Intent(this,AddLog.class);
Toolbar toolbar = (Toolbar)findViewById(R.id.maintoolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Account's");
getSupportLoaderManager().initLoader(1,null,this);
adapter = new Mainrow_Adapter(this,null);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
public void createID(View view)
{
ContentValues values = new ContentValues();
values.put(DataProvider.Pname,"1");
values.put(DataProvider.Pphone,"1");
values.put(DataProvider.Paddress,"1");
values.put(DataProvider.PCategory,"1");
values.put(DataProvider.Pamount,"1");
getContentResolver().insert(DataProvider.ContentUri_Person,values);
long id = DataProvider.insertId;
addDisplay.putExtra("ID",id);
Toast.makeText(MainActivity.this,String.valueOf(id), Toast.LENGTH_SHORT).show();
startActivity(addDisplay);
finish();
}
#Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] Prjection = {DataProvider.PID,DataProvider.Pname,DataProvider.Pphone,DataProvider.Paddress,DataProvider.PCategory,DataProvider.Pamount};
return new CursorLoader(this,DataProvider.ContentUri_Person,Prjection,null,null,null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
{
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader)
{
adapter.swapCursor(null);
}
}
AddLog activity class :
public class AddLog extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{
TextView TotalAmount,Date;
EditText name,mobile,city,detailname,detailamount;
RecyclerView adddetailtolist;
DetailsAdapter adapter;
Intent returnback;
double totamount;
long logid;
String Debt = "Debt";
String Paid = "Paid";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_log);
Toolbar toolbar = (Toolbar)findViewById(R.id.addlogtoolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Add Log");
returnback = new Intent(this,MainActivity.class);
Intent intent = getIntent();
logid = intent.getExtras().getLong("ID");
TotalAmount = (TextView)findViewById(R.id.totalAmount);
Date = (TextView)findViewById(R.id.addlogDate);
name = (EditText)findViewById(R.id.AddName);
mobile = (EditText)findViewById(R.id.AddPhone);
city = (EditText)findViewById(R.id.Addcity);
detailname = (EditText)findViewById(R.id.Detailname);
detailamount = (EditText)findViewById(R.id.Detailamount);
adddetailtolist = (RecyclerView)findViewById(R.id.addloglist);
Date.setText(getDate());
getSupportLoaderManager().initLoader(1,null,this);
adapter = new DetailsAdapter(this,null);
adddetailtolist.setAdapter(adapter);
adddetailtolist.setLayoutManager(new LinearLayoutManager(this));
}
private String getDate()
{
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE,dd-MMM-yyyy");
String date = simpleDateFormat.format(calendar.getTime());
return date;
}
public void addDetails(View view)
{
String Name = detailname.getText().toString();
String Amount = detailamount.getText().toString();
String date = Date.getText().toString();
ContentValues contentValues = new ContentValues();
contentValues.put(DataProvider.Dname,Name);
contentValues.put(DataProvider.DCategory,Debt);
contentValues.put(DataProvider.Damount,Amount);
contentValues.put(DataProvider.Ddate,date);
contentValues.put(DataProvider.Per_In,logid);
Uri uri = getContentResolver().insert(DataProvider.ContentUri_Details,contentValues);
Toast.makeText(AddLog.this, uri.toString()+"Value Inserted", Toast.LENGTH_SHORT).show();
NumberFormat currency = changeamount();
TotalAmount.setText(currency.format(getAmount()));
}
private double getAmount()
{
ContentProviderClient client = getContentResolver().acquireContentProviderClient(DataProvider.ContentUri_Details);
SQLiteDatabase db = ((DataProvider)client.getLocalContentProvider()).sqLiteDatabase;
String query = "SELECT SUM(DAmount) FROM Details WHERE Per_In = "+logid;
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
double amount = cursor.getDouble(0);
cursor.close();
client.release();
return amount;
}
public NumberFormat changeamount()
{
Locale locale = new Locale("en","IN");
NumberFormat currencyformat = NumberFormat.getCurrencyInstance(locale);
return currencyformat;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinflate = getMenuInflater();
menuinflate.inflate(R.menu.addlogmenu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.done:
saveData();
}
return super.onOptionsItemSelected(item);
}
private void saveData()
{
String name1 = name.getText().toString();
String phone = mobile.getText().toString();
String address = city.getText().toString();
if (TextUtils.isEmpty(name1)||TextUtils.isEmpty(phone)||TextUtils.isEmpty(address))
{
if (TextUtils.isEmpty(name1))
{
name.setError("Feild can not be Empty");
}
else if (TextUtils.isEmpty(phone))
{
mobile.setError("Feild can not be Empty");
}
else if (TextUtils.isEmpty(address))
{
city.setError("Feild can not be Empty");
}
}
else
{
ContentValues values = new ContentValues();
values.put(DataProvider.Pname,name1);
values.put(DataProvider.Pphone,phone);
values.put(DataProvider.Paddress,address);
values.put(DataProvider.PCategory,"Debt");
values.put(DataProvider.Pamount,totamount);
String where = DataProvider.PID+"=?";
String[] whereargs = {String.valueOf(logid)};
int a = getContentResolver().update(DataProvider.ContentUri_Person,values,where,whereargs);
Toast.makeText(AddLog.this, String.valueOf(1)+"Value updated", Toast.LENGTH_SHORT).show();
startActivity(returnback);
finish();
}
}
#Override
public Loader<Cursor> onCreateLoader(final int id, Bundle args)
{
String[] Projection = new String[]{DataProvider.DID,DataProvider.Dname,DataProvider.DCategory,DataProvider.Damount,DataProvider.Ddate};
String selection = DataProvider.Per_In+"=?";
String[] selectionargs = new String[]{String.valueOf(logid)};
return new CursorLoader(this,DataProvider.ContentUri_Details,Projection,selection,selectionargs,null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
{
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader)
{
adapter.swapCursor(null);
}
}
Content Provider class:
public class DataProvider extends ContentProvider
{
static final String ProviderName = "com.example.mrudu.accounts.provider";
static final String URLPerson = "content://"+ProviderName+"/Person_Detail";
static final String URLDetails = "content://"+ProviderName+"/Details";
static final Uri ContentUri_Person = Uri.parse(URLPerson);
static final Uri ContentUri_Details = Uri.parse(URLDetails);
//Tables
private static String PTableName = "Person_Detail";
private static String DTableName = "Details";
public static long insertId = 0;
//Person_Detail Coloumns
public static String PID = "_id";
public static String Pname = "PName";
public static String Pphone = "PMobile";
public static String Paddress = "PCity";
public static String PCategory = "PCategory";
public static String Pamount = "PAmount";
//Details coloumn
public static String DID = "_id";
public static String Dname = "DName";
public static String Damount = "DAmount";
public static String Ddate = "DDate";
public static String DCategory = "DCategory";
public static String Per_In = "Per_In";
private static final int Person = 1;
private static final int Person_ID = 2;
private static final int Details = 3;
private static final int Details_Id = 4;
static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static
{
uriMatcher.addURI(ProviderName,PTableName,Person);
uriMatcher.addURI(ProviderName,PTableName+"/#",Person_ID);
uriMatcher.addURI(ProviderName,DTableName,Details);
uriMatcher.addURI(ProviderName,DTableName+"/#",Details_Id);
}
public static SQLiteDatabase sqLiteDatabase;
private static String Databasename = "Accounts";
private static int DatabaseVersion = 1;
private class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper(Context context)
{
super(context, Databasename, null, DatabaseVersion);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase)
{
String Create_Person = " Create Table "+PTableName+"("+PID+" INTEGER PRIMARYKEY ,"+Pname+" TEXT ,"+Pphone+" TEXT ,"+Paddress+" TEXT ,"+PCategory+" TEXT ,"+Pamount+" REAL"+")";
String Create_Details = " Create Table "+DTableName+"("+DID+" INTEGER PRIMARYKEY ,"+Dname+" TEXT ,"+DCategory+" TEXT ,"+Damount+" REAl ,"+Ddate+" TEXT ,"+Per_In+" INTEGER )";
sqLiteDatabase.execSQL(Create_Person);
sqLiteDatabase.execSQL(Create_Details);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1)
{
sqLiteDatabase.execSQL("Drop TABLE if exists"+PTableName);
sqLiteDatabase.execSQL("Drop TABLE if exists"+DTableName);
onCreate(sqLiteDatabase);
}
}
#Override
public boolean onCreate()
{
Context context = getContext();
DatabaseHelper databaseHelper = new DatabaseHelper(context);
sqLiteDatabase = databaseHelper.getWritableDatabase();
return (sqLiteDatabase==null)?false:true;
}
#Override
public Uri insert(Uri uri, ContentValues values)
{
switch (uriMatcher.match(uri))
{
case Person:
long rowId = sqLiteDatabase.insert(PTableName,null,values);
insertId = rowId;
if (rowId>0)
{
Uri _uri = ContentUris.withAppendedId(ContentUri_Person,rowId);
getContext().getContentResolver().notifyChange(_uri,null);
return _uri;
}
break;
case Details:
long rowId1 = sqLiteDatabase.insert(DTableName,null,values);
if (rowId1>0)
{
Uri _uri = ContentUris.withAppendedId(ContentUri_Details,rowId1);
getContext().getContentResolver().notifyChange(_uri,null);
return _uri;
}
break;
}
return null;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder)
{
SQLiteQueryBuilder sqLiteQueryBuilder = new SQLiteQueryBuilder();
switch (uriMatcher.match(uri))
{
case Person_ID:
sqLiteQueryBuilder.setTables(PTableName);
sqLiteQueryBuilder.appendWhere(PID+ "="+ uri.getPathSegments().get(1));
break;
case Person:
sqLiteQueryBuilder.setTables(PTableName);
break;
case Details_Id:
sqLiteQueryBuilder.setTables(DTableName);
sqLiteQueryBuilder.appendWhere(Per_In +"="+ uri.getPathSegments().get(1));
break;
case Details:
sqLiteQueryBuilder.setTables(DTableName);
break;
default:
throw new UnsupportedOperationException("Not yet implemented");
}
Cursor cursor = sqLiteQueryBuilder.query(sqLiteDatabase,projection,selection,selectionArgs,null,null,sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(),uri);
return cursor;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs)
{
int count = 0;
switch (uriMatcher.match(uri))
{
case Person:
count = sqLiteDatabase.update(PTableName,values,selection,selectionArgs);
break;
case Person_ID:
count = sqLiteDatabase.update(PTableName,values,PID+" = "+uri.getPathSegments().get(1)+(!TextUtils.isEmpty(selection)?" AND (" + selection + ')':""),selectionArgs);
break;
case Details:
count = sqLiteDatabase.update(DTableName,values,selection,selectionArgs);
break;
case Details_Id:
count = sqLiteDatabase.update(DTableName,values,Per_In+" = "+uri.getPathSegments().get(1)+(!TextUtils.isEmpty(selection)?" AND (" + selection + ')':""),selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri );
}
getContext().getContentResolver().notifyChange(uri,null);
return count;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Implement this to handle requests to delete one or more rows.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public String getType(Uri uri) {
// TODO: Implement this to handle requests for the MIME type of the data
// at the given URI.
throw new UnsupportedOperationException("Not yet implemented");
}
Cursor Recyclerview Adapter class:
public abstract class CursorRecyclerViewAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
private Context mContext;
private Cursor mCursor;
private boolean mDataValid;
private int mRowIdColumn;
private DataSetObserver mDataSetObserver;
public CursorRecyclerViewAdapter(Context context, Cursor cursor) {
mContext = context;
mCursor = cursor;
mDataValid = cursor != null;
mRowIdColumn = mDataValid ? mCursor.getColumnIndex("_id") : -1;
mDataSetObserver = new NotifyingDataSetObserver();
if (mCursor != null) {
mCursor.registerDataSetObserver(mDataSetObserver);
}
}
public Cursor getCursor() {
return mCursor;
}
#Override
public int getItemCount() {
if (mDataValid && mCursor != null) {
return mCursor.getCount();
}
return 0;
}
#Override
public long getItemId(int position) {
if (mDataValid && mCursor != null && mCursor.moveToPosition(position)) {
return mCursor.getLong(mRowIdColumn);
}
return 0;
}
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(true);
}
public abstract void onBindViewHolder(VH viewHolder, Cursor cursor);
#Override
public void onBindViewHolder(VH viewHolder, int position) {
if (!mDataValid) {
throw new IllegalStateException("this should only be called when the cursor is valid");
}
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
onBindViewHolder(viewHolder, mCursor);
}
/**
* Change the underlying cursor to a new cursor. If there is an existing cursor it will be
* closed.
*/
public void changeCursor(Cursor cursor) {
Cursor old = swapCursor(cursor);
if (old != null) {
old.close();
}
}
/**
* Swap in a new Cursor, returning the old Cursor. Unlike
* {#link #changeCursor(Cursor)}, the returned old Cursor is <em>not</em>
* closed.
*/
public Cursor swapCursor(Cursor newCursor) {
if (newCursor == mCursor) {
return null;
}
final Cursor oldCursor = mCursor;
if (oldCursor != null && mDataSetObserver != null) {
oldCursor.unregisterDataSetObserver(mDataSetObserver);
}
mCursor = newCursor;
if (mCursor != null) {
if (mDataSetObserver != null) {
mCursor.registerDataSetObserver(mDataSetObserver);
}
mRowIdColumn = newCursor.getColumnIndexOrThrow("_id");
mDataValid = true;
notifyDataSetChanged();
} else {
mRowIdColumn = -1;
mDataValid = false;
notifyDataSetChanged();
//There is no notifyDataSetInvalidated() method in RecyclerView.Adapter
}
return oldCursor;
}
private class NotifyingDataSetObserver extends DataSetObserver {
#Override
public void onChanged() {
super.onChanged();
mDataValid = true;
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
super.onInvalidated();
mDataValid = false;
notifyDataSetChanged();
//There is no notifyDataSetInvalidated() method in RecyclerView.Adapter
}
}
}
Main Adapter class:
public class Mainrow_Adapter extends CursorRecyclerViewAdapter<Mainrow_Adapter.ViewHolder>
{
public Mainrow_Adapter(Context context, Cursor cursor) {
super(context, cursor);
}
public static class ViewHolder extends RecyclerView.ViewHolder
{
TextView mName,mAmount;
public ViewHolder(View itemView) {
super(itemView);
mName = (TextView)itemView.findViewById(R.id.mainrowname);
mAmount = (TextView)itemView.findViewById(R.id.mainrowAmount);
}
}
#Override
public Mainrow_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.mainrow_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(Mainrow_Adapter.ViewHolder viewHolder, Cursor cursor)
{
PersonDetails personDetails = PersonDetails.from(cursor);
viewHolder.mName.setText(personDetails.getName());
viewHolder.mAmount.setText(String.valueOf(personDetails.getAmount()));
}
}
Ok,
then move below three lines from onCreate method to onResume(),
getSupportLoaderManager().initLoader(1,null,this);
adapter = new Mainrow_Adapter(this,null);
recyclerView.setAdapter(adapter);
Hope this will work

Android How to detect contact list is changed?

I have implemented a ContentObserver, using this method I'm only able to be notified if a change occurs on a contact
but I don't know which contact has been added , deleted or updated ??
! Any suggestions ? how do i know which particular contact is modified ?
i am getting all contact list by using following method .
public void readContacts() {
System.out.println(" reading contact ");
String phoneNumber = 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;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor
.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor
.getColumnIndex(DISPLAY_NAME));
// int id =
// Integer.parseInt(cursor.getString(cursor.getColumnIndex(
// HAS_PHONE_NUMBER )));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor
.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
System.out.println(" CONTACT NAME : " + name);
Contact_Name.add(name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?",
new String[] { contact_id }, null);
phoneCursor.moveToNext();
phoneNumber = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
System.out.println(" CONTACT number : " + phoneNumber);
phoneNumber = phoneNumber.replaceAll("\\s", "");
// phoneNumber = phoneNumber.substring(phoneNumber.length()
// - 10);
// System.err.println("Mobile no."+phoneNumber);
Contact_Number.add(phoneNumber);
phoneCursor.close();
}
output.append("\n");
}
}
}
and i am observing contact list is being some changed by regestring and using following code .
this.getContentResolver().registerContentObserver(
ContactsContract.Contacts.CONTENT_URI, true, mObserver);
private ContentObserver mObserver = new ContentObserver(new Handler()) {
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
final int currentCount = getContactCount();
if (currentCount < mContactCount) {
System.out.println(" Deleted contact");
} else if (currentCount == mContactCount) {
System.out.println(" upated contact");
} else {
System.out.println(" inserted contact");
}
mContactCount = currentCount;
}
};
Check if the version is greater than the one you have already (for the current contact). This is fast and more accurate then the current process your are following, since OnChange is called for all the items (delete, add or update).
So counting the # of contacts doesn't make much sense because a contact would have been updated then deleted and new contact added. the count is same in this case.
http://developer.android.com/reference/android/provider/ContactsContract.SyncColumns.html#VERSION
Try to use this implementation for you Contacts array
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ActiveList<T> extends ArrayList<T> implements Serializable {
private static final long serialVersionUID = 870605912858223939L;
transient private List<ActiveListListener<T>> listeners;
public interface ActiveListListener<T> {
void onAdd(T item);
void onInsert(int location, T item);
void onAddAll(Collection<? extends T> items);
void onClear();
}
#Override
public synchronized void clear() {
super.clear();
fireChangedEvent();
}
#Override
public synchronized int size() {
return super.size();
}
#Override
public synchronized T get(int index) {
return super.get(index);
}
#Override
public synchronized boolean add(T item) {
boolean success = super.add(item);
if (success) {
fireAddEvent(item);
}
return success;
}
#Override
public synchronized void add(int index, T item) {
super.add(index, item);
fireInsertEvent(index, item);
}
#Override
public synchronized boolean addAll(int index, Collection<? extends T> items) {
boolean success = super.addAll(index, items);
if (success) {
fireAddAllEvent(items);
}
return success;
}
#Override
public synchronized boolean addAll(Collection<? extends T> items) {
boolean success = super.addAll(items);
if (success) {
fireAddAllEvent(items);
}
return success;
}
public synchronized void addListener(ActiveListListener<T> listener) {
if (this.listeners == null) {
listeners = Lists.newArrayList();
}
this.listeners.add(listener);
}
public synchronized void removeListener(ActiveListListener<T> listener) {
if (this.listeners != null) {
this.listeners.remove(listener);
}
}
private void fireChangedEvent() {
if (this.listeners == null)
return;
for (ActiveListListener<T> listener : listeners) {
listener.onClear();
}
}
private void fireInsertEvent(int location, T item) {
if (this.listeners == null)
return;
for (ActiveListListener<T> listener : listeners) {
listener.onInsert(location, item);
}
}
private void fireAddEvent(T item) {
if (this.listeners == null)
return;
for (ActiveListListener<T> listener : listeners) {
listener.onAdd(item);
}
}
private void fireAddAllEvent(Collection<? extends T> items) {
if (this.listeners == null)
return;
for (ActiveListListener<T> listener : listeners) {
listener.onAddAll(items);
}
}
}
In your Activity or Adapter
protected ActiveList.ActiveListListener<Contact> activeListListener = new ActiveList.ActiveListListener<Contact>() {
#Override
public void onAdd(Contact c) {
// do something
}
#Override
public void onInsert(final int location, final Contact c) {
// do something
}
#Override
public void onClear() {
// do something
}
#Override
public void onAddAll(List<Contact> cs) {
// do something
}
};
and in your Array
((ActiveList<Contact>) this.contacts).addListener(activeListListener);
See example https://github.com/davidevallicella/UnivrApp/

SQLite in Android: do I have to download any SQLite Administration (like MySQL) or it is already in device memory?

I need to work with SQLite in Android.
So, do I have to download any SQLite Administration (like MySql) or it is already in device memory?
All you need is already installed. To inspect the database during development you can use the sqlite3 tool. It is installed in the emulator.
You Don't need to download anything.its already there.
You don't have to do anything besides using the built-in tools in the Android SDK. For more information please have a look at the sqlite documentation
Basically you can use Java code to create databases, insert records into them, modify them etc.
If you want a graphical way to work on the databases, simply use Eclipse's DDMS View to navigate into your app's databases folder. From there, download the database on your computer and open it with one of the many sqlite applications available.
------------------------------------------------------------------------
Sqlite
----------------------------------------------------------------------
// instance varieable
Button btn_insert,btn_update,btn_show,btn_delete,btn_search;
EditText edit_no,edit_name,edit_mark;
Cursor c;
Context context=this;
SQLiteDatabase db;
StringBuffer sb;
init
edit_no= (EditText) findViewById(R.id.edit_no);
edit_name= (EditText) findViewById(R.id.edit_name);
edit_mark= (EditText) findViewById(R.id.edit_mark);
btn_insert= (Button) findViewById(R.id.btn_insert);
btn_update= (Button) findViewById(R.id.btn_update);
btn_show= (Button) findViewById(R.id.btn_show);
btn_delete= (Button) findViewById(R.id.btn_delete);
btn_search= (Button) findViewById(R.id.btn_search);
db=openOrCreateDatabase("topstech",context.MODE_PRIVATE,null);
db.execSQL("create table if not exists register(no varchar2(20),name varchar2(20),mark varchar2(20))");
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (edit_no.getText().toString().trim().length() == 0) {
edit_no.setError("Enter Your No");
return;
} else if (edit_name.getText().toString().trim().length() == 0) {
edit_name.setError("Enter Your Name");
return;
} else if (edit_mark.getText().toString().trim().length() == 0) {
edit_mark.setError("Enter Your Mark");
return;
} else {
db.execSQL("insert into register values('" + edit_no.getText().toString() + "','" + edit_name.getText().toString() + "','" + edit_mark.getText().toString() + "')");
Toast.makeText(context, "Record Successfully Inserted...", Toast.LENGTH_SHORT).show();
Clear();
}
}
});
btn_show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
c=db.rawQuery("select * from register",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
sb.append(c.getString(c.getColumnIndex("no"))+"\t");
sb.append(c.getString(c.getColumnIndex("name"))+"\t");
sb.append(c.getString(c.getColumnIndex("mark"))+"\n");
}while (c.moveToNext());
Toast.makeText(MainActivity.this, ""+sb, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Empty Record...", Toast.LENGTH_SHORT).show();
}
}
});
btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
db.execSQL("delete from register where no='"+edit_no.getText().toString()+"'");
Toast.makeText(MainActivity.this, "1 Record Is Deleted...", Toast.LENGTH_SHORT).show();
Clear();
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
btn_search.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
edit_name.setText(c.getString(c.getColumnIndex("name")));
edit_mark.setText(c.getString(c.getColumnIndex("mark")));
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
if (edit_name.getText().toString().trim().length() == 0)
{
edit_name.setError("Enter Your Name");
return;
}
else if (edit_mark.getText().toString().trim().length() == 0)
{
edit_mark.setError("Enter Your Mark");
return;
}
else
{
//Syntex:-
// db.execSQL("update tablename set col_name='" +edit_name+"' where no='" + no+ "'");
db.execSQL("update register set name='"+edit_name.getText().toString()+"',mark='"+edit_mark.getText().toString()+"' where no='"+edit_no.getText().toString()+"'");
Toast.makeText(MainActivity.this, "1 Record Is Updated...", Toast.LENGTH_SHORT).show();
Clear();
}
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
}
-----------------------------------------
Upload Image ANd Fetch Device Contact JSON ARRAY
------------------------------------------
Upload Image Using Retrofit
#Multipart
#POST("addDocument")
Call<AddDocumentsResponse> doAddDocuments(#Header("Authorization") String token, #Part List<MultipartBody.Part> files, #PartMap Map<String, RequestBody> map);
private void uploadDocuments() {
if (Utility.checkInternetConnection(InsurenceActivity.this)) {
ArrayList<MultipartBody.Part> multipart = new ArrayList<>();
Map<String, RequestBody> map = new HashMap<>();
map.put("document_type", RequestBody.create(MediaType.parse("text/plain"), "insurance"));
map.put("expiry_date", RequestBody.create(MediaType.parse("text/plain"), str_select_date));
map.put("photo_id_type", RequestBody.create(MediaType.parse("text/plain"), ""));
multipart.add(Utility.prepareFilePart(InsurenceActivity.this, "document_file", picturePath));
messageUtil.showProgressDialog(InsurenceActivity.this);
Call<AddDocumentsResponse> registerResponseCall = ApiClient.getApiInterface().doAddDocuments(fastSave.getString(Constant.ACCESS_TOKEN), multipart, map);
Log.d("request","---- Request -----"+map.toString());
registerResponseCall.enqueue(new Callback<AddDocumentsResponse>() {
#Override
public void onResponse(Call<AddDocumentsResponse> call, Response<AddDocumentsResponse> response) {
if (response.code() == 200) {
if (response.body().getStatus().equalsIgnoreCase("fail"))
{
messageUtil.hideProgressDialog();
messageUtil.showErrorToast(response.body().getMessage());
return;
}
if (response.body().getStatus().equalsIgnoreCase("success"))
{
Log.d("response","---- Respons -----"+new Gson().toJson(response));
messageUtil.hideProgressDialog();
messageUtil.showSuccessToast(response.body().getMessage());
str_select_date = str_select_date;
picturePath = null;
Log.d("TAG", "success:............... " + new Gson().toJson(response));
finish();
}
}
}
#Override
public void onFailure(Call<AddDocumentsResponse> call, Throwable t) {
messageUtil.hideProgressDialog();
messageUtil.showErrorToast("Something went wrong");
}
});
} else {
Toast.makeText(this, R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
}
}
public static MultipartBody.Part prepareFilePart(Context context, String partName, String filePath) {
if(filePath!=null) {
File file = new File(filePath);
Log.d("TAG", "prepareFilePart: " + filePath);
// RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(Uri.fromFile(file))), file);
// Libaray Required
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
// Multipart Camera and Gallery
// RequestBody requestBody = RequestBody.create(MediaType.parse(context.getContentResolver().getType(FileProvider.getUriForFile(context, "com.", file))), file);
return MultipartBody.Part.createFormData(partName, file.getName(), requestBody);
}
else {
return MultipartBody.Part.createFormData(partName,"");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
ll_profile_file.setVisibility(View.GONE);
img_photo_file.setVisibility(VISIBLE);
img_photo_file.setImageURI(resultUri);
picturePath = resultUri.getPath();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
}
}
}
Fetch Device Contact Fast
ArrayList<Contact> listContacts;
listContacts = new ContactFetcher(this).fetchAll();
public class ContactPhone {
public String number;
public String type;
public ContactPhone(String number, String type) {
this.number = number;
this.type = type;
}
}
public class ContactFetcher {
private final Context context;
public ContactFetcher(Context c) {
this.context = c;
}
public ArrayList<Contact> fetchAll() {
String[] projectionFields = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
ArrayList<Contact> listContacts = new ArrayList<>();
CursorLoader cursorLoader = new CursorLoader(context,
ContactsContract.Contacts.CONTENT_URI,
projectionFields, // the columns to retrieve
null, // the selection criteria (none)
null, // the selection args (none)
null // the sort order (default)
);
Cursor c = cursorLoader.loadInBackground();
final Map<String, Contact> contactsMap = new HashMap<>(c.getCount());
if (c.moveToFirst()) {
int idIndex = c.getColumnIndex(ContactsContract.Contacts._ID);
int nameIndex = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
do {
String contactId = c.getString(idIndex);
String contactDisplayName = c.getString(nameIndex);
Contact contact = new Contact(contactId, contactDisplayName);
contactsMap.put(contactId, contact);
listContacts.add(contact);
} while (c.moveToNext());
}
c.close();
matchContactNumbers(contactsMap);
matchContactEmails(contactsMap);
return listContacts;
}
public void matchContactNumbers(Map<String, Contact> contactsMap) {
// Get numbers
final String[] numberProjection = new String[]{
Phone.NUMBER,
Phone.TYPE,
Phone.CONTACT_ID,
};
Cursor phone = new CursorLoader(context,
Phone.CONTENT_URI,
numberProjection,
null,
null,
null).loadInBackground();
if (phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER);
final int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE);
final int contactIdColumnIndex = phone.getColumnIndex(Phone.CONTACT_ID);
while (!phone.isAfterLast()) {
final String number = phone.getString(contactNumberColumnIndex);
final String contactId = phone.getString(contactIdColumnIndex);
Contact contact = contactsMap.get(contactId);
if (contact == null) {
continue;
}
final int type = phone.getInt(contactTypeColumnIndex);
String customLabel = "Custom";
CharSequence phoneType = Phone.getTypeLabel(context.getResources(), type, customLabel);
contact.addNumber(number, phoneType.toString());
phone.moveToNext();
}
}
phone.close();
}
public void matchContactEmails(Map<String, Contact> contactsMap) {
// Get email
final String[] emailProjection = new String[]{
Email.DATA,
Email.TYPE,
Email.CONTACT_ID,
};
Cursor email = new CursorLoader(context,
Email.CONTENT_URI,
emailProjection,
null,
null,
null).loadInBackground();
if (email.moveToFirst()) {
final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);
final int contactTypeColumnIndex = email.getColumnIndex(Email.TYPE);
final int contactIdColumnsIndex = email.getColumnIndex(Email.CONTACT_ID);
while (!email.isAfterLast()) {
final String address = email.getString(contactEmailColumnIndex);
final String contactId = email.getString(contactIdColumnsIndex);
final int type = email.getInt(contactTypeColumnIndex);
String customLabel = "Custom";
Contact contact = contactsMap.get(contactId);
if (contact == null) {
continue;
}
CharSequence emailType = Email.getTypeLabel(context.getResources(), type, customLabel);
contact.addEmail(address, emailType.toString());
email.moveToNext();
}
}
email.close();
}
public class ContactEmail {
public String address;
public String type;
public ContactEmail(String address, String type) {
this.address = address;
this.type = type;
}
}
public class Contact {
public String id;
public String name;
public ArrayList<ContactEmail> emails;
public ArrayList<ContactPhone> numbers;
public Contact(String id, String name) {
this.id = id;
this.name = name;
this.emails = new ArrayList<ContactEmail>();
this.numbers = new ArrayList<ContactPhone>();
}
#Override
public String toString() {
String result = name;
if (numbers.size() > 0) {
ContactPhone number = numbers.get(0);
result += " (" + number.number + " - " + number.type + ")";
}
if (emails.size() > 0) {
ContactEmail email = emails.get(0);
result += " [" + email.address + " - " + email.type + "]";
}
return result;
}
public void addEmail(String address, String type) {
emails.add(new ContactEmail(address, type));
}
public void addNumber(String number, String type) {
numbers.add(new ContactPhone(number, type));
}
JSON ARRAY
Model model = new Model();
ArrayList<Model> contacts_arraylist=new ArrayList<>();
for (int i = 0; i < 50; i++)
{
model.setName("sanjay"+i);
model.setEmails("sanjay#gmail.com"+i);
model.setNumbers("89689527"+i);
contacts_arraylist.add(model);
}
JSONArray personarray=new JSONArray();
for (int j = 0; j < contacts_arraylist.size(); j++)
{
JSONObject person1 = new JSONObject();
try {
if(contacts_arraylist.get(j).getName()!=null)
{
person1.put("name", contacts_arraylist.get(j).getName());
}
else {
person1.put("name","");
}
if(contacts_arraylist.get(j).getEmails().length()>0)
{
person1.put("email", contacts_arraylist.get(j).getEmails());
}
else {
person1.put("email", "");
}
if(contacts_arraylist.get(j).getNumbers().length()>0)
{
person1.put("mobile_number", contacts_arraylist.get(j).getNumbers());
}
else {
person1.put("mobile_number", "");
}
personarray.put(person1);
} catch (JSONException e)
{
e.printStackTrace();
}
}
txt_array.setText(personarray.toString());
System.out.println("jsonString:---- " + personarray.toString());
}

Categories

Resources