I am trying to edit a group title and Notes,
Editing title works for both system groups and user created groups,
Although notes column only persist if it is a System group(e.g. "Contacts", "Friends", "Family", "Coworkers"),
I assume that it either doesn't save notes for user created groups or some how gets overwritten with title column content in notes column.
How can I use notes column in contact groups? is there any other way to store additional information with groups?
Here is my code snippet:
ArrayList<ContentProviderOperation> ops =new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder op =
ContentProviderOperation.newUpdate(ContactsContract.Groups.CONTENT_URI)
.withSelection(ContactsContract.Groups._ID + "="+group.getId(), null)
.withValue(ContactsContract.Groups.TITLE, group.getTitle());
HashMap<String, String> notes = group.getNotes();
if(notes!=null && notes.size()>0){
op = op.withValue(ContactsContract.Groups.NOTES, new Gson().toJson(group.getNotes()));
}
ops.add(op.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
Hope this solution works for you, seems to be working for me.
I've used ContentResolver.update() method.
I assume that it either doesn't save notes for user created groups or some how gets overwritten with title column content in notes column.
I was able to update the notes for user created groups using below code.
How can I use notes column in contact groups?
You can use notes column to save any TEXT value because it's defined of type TEXT in sqlite. See ContactsContract.Groups.NOTES .
(Tested on Google Pixel XL, Oreo 8.0.0)
public class MainActivity extends AppCompatActivity {
private Cursor mCursor;
private SimpleCursorAdapter adapter;
private ListView lvGroups;
#Override
protected void onDestroy() {
if (mCursor != null)
mCursor.close();
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvGroups = findViewById(R.id.lvGroups);
checkAndRequestPermission();
}
private void checkAndRequestPermission() {
if (PermissionChecker.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PermissionChecker.PERMISSION_GRANTED) {
loadGroups();
} else {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS}, 123);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean isGranted = true;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == PermissionChecker.PERMISSION_DENIED)
isGranted = false;
}
if (isGranted)
loadGroups();
else
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS},123);
}
private void loadGroups() {
mCursor = getContentResolver().query(ContactsContract.Groups.CONTENT_URI,null,ContactsContract.Groups.GROUP_IS_READ_ONLY + " = 0",null, ContactsContract.Groups.TITLE);
adapter = new SimpleCursorAdapter(this, R.layout.contact_group_item, mCursor, new String[] {
ContactsContract.Groups.TITLE,
ContactsContract.Groups._ID,
ContactsContract.Groups.ACCOUNT_NAME,
ContactsContract.Groups.ACCOUNT_TYPE,
ContactsContract.Groups.AUTO_ADD,
ContactsContract.Groups.GROUP_IS_READ_ONLY,
ContactsContract.Groups.GROUP_VISIBLE,
ContactsContract.Groups.SOURCE_ID,
ContactsContract.Groups.NOTES},
new int[] {
R.id.text1,
R.id.text2,R.id.text3, R.id.text4, R.id.text5, R.id.text6, R.id.text7, R.id.text8, R.id.text9}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
lvGroups.setAdapter(adapter);
lvGroups.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(position);
int groupId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Groups._ID));
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Groups.NOTES,"My test Notes");
getContentResolver().update(ContactsContract.Groups.CONTENT_URI, contentValues, ContactsContract.Groups._ID + " = " + groupId, null);
adapter.notifyDataSetChanged();
}
});
}
}
The NOTES field is a String, it looks like you're trying to set a JSON object to it.
Check if this is working for you:
if (notes!=null && notes.size()>0) {
op = op.withValue(ContactsContract.Groups.NOTES, "TEST STRING!");
}
If so, you'll need to extract the actual string you need from the JSON object, that would depend on the format of your JSON.
Related
I need to fetch out the list of contacts that are recently used in last 24 hours and most frequently used.
I have searched a lot but did not find any way to do that. I also come to know that google has revoked the URIs to get frequently used contacts : https://developer.android.com/reference/android/provider/ContactsContract.Contacts#CONTENT_FREQUENT_URI
But what is the substitute of this URI is not given?
Please let me know the ways to achieve:
Fetch list of contacts contacted recently in last 24 hours.
Fetch the top 3 most frequently used contacts.
The whole point of deprecating the CONTENT_FREQUENT_URI as well as the TIMES_CONTACTED and LAST_TIME_CONTACTED fields in the Contacts table are to prevent apps from accessing the information you're looking for.
Google now considers this info to be sensitive user info, and will not allow apps to obtain that going forward.
However, from my experience, it seems that all devices I know of or are used by our users still allow access to the deprecated API, so if you need something that will be ok for most of your users within the next year or so, you can still use it.
Code should be something like:
String[] projection = new String[] { Contacts._ID, Contacts.DISPLAY_NAME, Contacts.LAST_TIME_CONTACTED };
Cursor lastContacted = getContentResolver().query(Contacts.CONTENT_URI, projection, Contacts.LAST_TIME_CONTACTED + " < " + lastDayTimestamp, null, Contacts.LAST_TIME_CONTACTED + " DESC");
DatabaseUtils.dumpCursor(lastContacted);
Cursor mostContacted = getContentResolver().query(Contacts.CONTENT_URI, projection, null, null, Contacts.TIMES_CONTACTED + " DESC");
DatabaseUtils.dumpCursor(mostContacted); // might want to limit this to 3
public class MainActivity extends AppCompatActivity {
ListView listView ;
ArrayList<String> StoreContacts ;
ArrayAdapter<String> arrayAdapter ;
Cursor cursor ;
String name, phonenumber ;
public static final int RequestPermissionCode = 1 ;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listview1);
button = (Button)findViewById(R.id.button1);
StoreContacts = new ArrayList<String>();
EnableRuntimePermission();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GetContactsIntoArrayList();
arrayAdapter = new ArrayAdapter<String>(
MainActivity.this,
R.layout.contact_items_listview,
R.id.textView, StoreContacts
);
listView.setAdapter(arrayAdapter);
}
});
}
public void GetContactsIntoArrayList(){
cursor =
getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null, null, null);
while (cursor.moveToNext()) {
name =
cursor.getString(cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAM
E));
phonenumber =
cursor.getString(cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER));
StoreContacts.add(name + " " + ":" + " " + phonenumber);
}
cursor.close();
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(
MainActivity.this,
Manifest.permission.READ_CONTACTS))
{
Toast.makeText(MainActivity.this,"CONTACTS permission allows us to Access
CONTACTS app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.READ_CONTACTS}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this,"Permission Granted, Now your
application can access CONTACTS.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Permission Canceled, Now your
application cannot access CONTACTS.", Toast.LENGTH_LONG).show();
}
break;
}
}
}
Hello I have set up a simple listview which is populated by a SQL database hence why I'm using a cursor adapter. I have now added a switch to the custom layout but now I need it to simply function by displaying a toast message with its current row position. Could you please have quick look at my code a guide me in the right direction.
Main Activity............
SimpleCursorAdapter simpleCursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
alarmListView = (ListView)findViewById(R.id.alarmListView);
databaseHandler = new MyDatabaseHandler(this, null, null, 1);
displayProductList();
}
private void displayProductList() {
try
{
Cursor cursor = databaseHandler.getAllProducts();
if (cursor == null)
{
return;
}
if (cursor.getCount() == 0)
{
return;
}
String[] columns = new String[] {
MyDatabaseHandler.COLUMN_AlARMDATE,
MyDatabaseHandler.COLUMN_ALARMTIME,
MyDatabaseHandler.COLUMN_ALARMNAME
};
int[] boundTo = new int[] {
R.id.custom_Date,
R.id.custom_Time,
R.id.custom_Name
};
simpleCursorAdapter = new SimpleCursorAdapter(this,
R.layout.alarm_list,
cursor,
columns,
boundTo,
0);
alarmListView.setAdapter(simpleCursorAdapter);
}
catch (Exception ex)
{
}
}
The other two remaining sections are simply my database and getters and setters.
Thank you
I am developing an application in which I list the device contacts, and perform some manipulation with them. I listen to contact changes as described in the following links: Link 1, Link 2
My code is as follows:
public class ContactService extends Service {
private int mContactCount;
Cursor cursor = null;
private int contactStateCheckingFlag=0;
static ContentResolver mContentResolver = null;
public static final String AUTHORITY = "com.example.contacts";
public static final String ACCOUNT_TYPE = "com.example.myapplication.account";
public static final String ACCOUNT = "myapplication";
Account mAccount;
Bundle settingsBundle;
int i=0;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();// Get contact count at start of service
mContactCount = getContactCount();
this.getContentResolver().registerContentObserver(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, true, mObserver);
Cursor curval = getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, null, null, null);
if (curval != null && curval.getCount() > 0) {
curval.getCount();
}
curval.close();
}
private int getContactCount() {
try {
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null,null);
if (cursor != null) {
return cursor.getCount();
} else {
cursor.close();
return 0;
}
} catch (Exception ignore) {
} finally {
cursor.close();
}
return 0;
}
private ContentObserver mObserver = new ContentObserver(new Handler()) {
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
new ContactServiceAsyncClass().execute();
}
};
private class ContactServiceAsyncClass extends AsyncTask<Void, Void, Void> {
ArrayList<Integer> arrayListContactID = new ArrayList<Integer>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
// Get the current count of contacts
int currentCount = getContactCount();
// Add New Contact
if (currentCount > mContactCount){
Cursor contactCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (contactCursor.getCount()<=0) {
Log.d("Contact Cursor count"," is zero");
}else {
Log.d("Contact Cursor count", " > 0");
// Fetch all contact ID from cursor
if(contactCursor.moveToFirst()){
do {
int contactID = contactCursor.getInt(contactCursor.getColumnIndex(ContactsContract.Data._ID));
arrayListContactID.add(contactID);
} while (contactCursor.moveToNext());
}
// Sort the array list having all contact ID
Collections.sort(arrayListContactID);
Integer maxID=Collections.max(arrayListContactID);
Log.d("maxID", ""+maxID);
// Get details of new added contact from contact id
String whereName = ContactsContract.Data._ID + " = ?";// Where condition
String[] whereNameParams = new String[] { ""+maxID}; // Pass maxID
Cursor cursorNewContact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, whereName, whereNameParams, null);
if(cursorNewContact.getCount()<=0){
}else {
if(cursorNewContact.moveToFirst()){
do{
// Fetch new added contact details
} while(cursorNewContact.moveToNext());
}
}
cursorNewContact.close();
}
contactCursor.close();
} else if(currentCount < mContactCount){
// Delete Contact/
// CONTACT DELETED.
} else if(currentCount == mContactCount){
// Update Contact1
}
mContactCount = currentCount;
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
I am able to fetch new added contact. The question is how to delete and update contact? How to know which contact is deleted and updated, as the contact change broadcast doesn't specify the id of the contact that changed?
Please provide your valuable suggestions and guide me in detail.
Thank you.
For delete operation,
1.First you store the previous list of contacts id in local database.
for example: you added contact id`s are 123,124,125.
Now we assume your last added contact(125) was deleted.
How we find it?.
simple first get the list of old contact list. and compare with current contact list.
If old contact list element not in the new list, that contact is deleted from phone.
Note: If delete operation complete, you need to update the contact id`s into DB.
For Update operation,
1.Use VERSION flag for indicating any changes in your contact.
2.VERSION default value is 1. if you modify the contacts,it automatically increase to 2.
3.So you need to store old version value in your local DB. and compare the version value increase or not. If increase the VERSION value you need to update this contact.
Refer the official link,
https://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html
For complete project,
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/4.0.4_r2.1/com/android/exchange/adapter/ContactsSyncAdapter.java?av=f
Alright... I've had enough.
I'm thoroughly frustrated.
So I'd rather ask for help instead of a new monitor.
...And those are VERY expensive here.
Long story short... I have a database. And a table.
private String DEFINE_PROP_TYPES = "CREATE TABLE " + TABLE_PROP_TYPES + "("
+ TABLE_ID + " INTEGER PRIMARY KEY, "
+ TABLE_PROP_TYPE_NAME + " TEXT NOT NULL"
+ ")";
With an 'Adapter' class thrown in for good measure to manage it.
public abstract class DBAdapter
{
static public final String C_COLUMN_ID = "_id";
protected Context context;
protected DBHelper dbHelper;
protected SQLiteDatabase db;
protected String managedTable;
protected String[] columns;
public String getTableManaged()
{
return managedTable;
}
public void setTableManaged(String managedTable)
{
this.managedTable = managedTable;
}
public void setColumns(String[] columns)
{
this.columns = columns;
}
public DBAdapter(Context context)
{
this.context = context;
}
public void close()
{
dbHelper.close();
}
public DBAdapter open() throws SQLException
{
dbHelper = new DBHelper(context);
db = dbHelper.getWritableDatabase();
return this;
}
public Cursor getList()
{
Cursor c = db.query(true, managedTable, columns, null, null, null, null, null, null);
return c;
}
public long insert(ContentValues reg)
{
return 0;
}
}
public class PropTypesDBAdapter extends DBAdapter
{
static public final String C_TABLE_PROP_TYPES = "PROP_TYPES";
static public final String C_COLUMN_ID = "_id",
C_COLUMN_PROP_TYPES_NAME = "re_prop_type";
public PropTypesDBAdapter(Context context)
{
super(context);
this.setTableManaged(C_TABLE_PROP_TYPES);
this.setColumns(new String[] { C_COLUMN_ID,
C_COLUMN_PROP_TYPES_NAME });
}
public long insert(ContentValues reg)
{
if (db == null)
{
open();
}
return db.insert(C_TABLE_PROP_TYPES, null, reg);
}
}
And besides this pile of cute I have an activity class.
With spinners.
public class PropDetailActivity extends Activity implements LocationListener
{
// insert here some blah-blah constants not needed by spinners
private PropDBAdapter mHouses;
private RatingsDBAdapter mRatings;
private PropTypesDBAdapter mPropTypes;
private Cursor mCursorHouses,
mCursorRatings,
mCursorPropTypes;
long mPropType;
private long mPropId;
private Spinner spinnerRating, spinnerType;
AdapterView.OnItemSelectedListener spnLstPropType, spnLstRating;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_house_detail);
Intent intent = getIntent();
Bundle extra = intent.getExtras();
if (extra == null)
{
return;
}
// Figure all view widgets being retrieved here, including...
spinnerRating = (Spinner) findViewById(R.id.spinnerRating);
spinnerType = (Spinner) findViewById(R.id.spinnerType);
// Create adapter and cursor-y things here
mHouses = new PropDBAdapter(this);
mHouses.open();
// And now, for the juicy, deliciously irritating stuff:
String[] from = new String[] { PropTypesDBAdapter.C_COLUMN_PROP_TYPES_NAME };
int[] to = new int[] { android.R.id.text1 };
mPropTypes = new PropTypesDBAdapter(this);
mPropTypes.open();
mCursorPropTypes = mPropTypes.getList();
#SuppressWarnings("deprecation")
SimpleCursorAdapter adapterPropTypes = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
mCursorPropTypes,
from, /*new String[] { RatingsDBAdapter.C_COLUMN_RATING_NAME }, */
to); /*new int[] { android.R.id.text1 } */
adapterPropTypes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerType.setAdapter(adapterPropTypes);
spinnerRating.setSelection(pos);
spnLstPropType = new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id)
{
mPropType = id;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) { }
};
spinnerType.setOnItemSelectedListener(spnLstPropType);
private int getItemPositionById(Cursor c, long id, DBAdapter adapter)
{
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
if (c.getLong(c.getColumnIndex(DBAdapter.C_COLUMN_ID)) == id)
{
return c.getPosition();
}
}
return 0;
}
private void query(long id)
{
mCursorHouses = mHouses.getRecord(id);
// Figure values being retrieved and set on their widgets instead of this comment... and now...
mPropType = mCursorHouses.getInt(mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_TYPE_ID));
spinnerType.setSelection(
getItemPositionById(
mCursorRatings,
mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_TYPE_ID),
mPropTypes
)
);
private void save()
{
ContentValues reg = new ContentValues();
// Read: values being put into 'reg'... eventually it should reach this:
reg.put(PropDBAdapter.C_PROP_TYPE_ID, mPropType);
try
{
if (mFormMode == PropListActivity.C_CREATE)
{
mHouses.insert(reg);
Toast.makeText(PropDetailActivity.this, R.string.house_create_notice, Toast.LENGTH_LONG).show();
}
else if (mFormMode == PropListActivity.C_EDIT)
{
Toast.makeText(PropDetailActivity.this, R.string.house_edit_notice, Toast.LENGTH_LONG).show();
reg.put(PropDBAdapter.C_COLUMN_ID, mPropId);
long resultCode = mHouses.update(reg);
Log.i(this.getClass().toString(), "Database operation result code: " + resultCode);
}
}
catch(SQLException e)
{
Log.i(this.getClass().toString(), e.getMessage());
}
setResult(RESULT_OK);
finish();
}
}
Spinners are being bad boys. Lazy bad boys on top of that.
They do load up the data -a list of real estate property types- they are meant to display.
After some spanking, that is.
But, hoping them to save THE VALUE YOU SELECT to SQLite? And to show THAT EXACT VALUE when fetching stuff back from the database?
Oh, no, no way no how.
They stubbornly stick to displaying always the same value upon activity startup.
So... please... I must draw upon your collective wisdom to save my sorry excuse for a project...
Pleasepleaseplease? :)
(IF you feel like diving into the whole uncut code, here's a GIT repository for you: https://github.com/CruxMDQ/Quoterv3)
Checking your code, I think I found the problem, change the following lines in your query method in PopDetailActivity.java.
For spinnerRating do:
spinnerRating.setSelection(
getItemPositionById(
mCursorRatings,
mCursorHouses.getInt(mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_RATING_ID)),
mRatings
)
);
and for spinnerType do:
spinnerType.setSelection(
getItemPositionById(
mCursorPropTypes,
mCursorHouses.getInt(mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_TYPE_ID)),
mPropTypes
)
);
EDIT:
In your query method, you initialize mPropTypeId, with the call to getItemPositionById() but in that call the first parameter should be mCursorPropTypes instead of mCursorHouses
A few things:
(1) I don't really see anywhere above where you actually create a SQLite database or use the SQLiteOpenHelper class to access that data. Take a look at this tutorial. It uses a simple single table set up to store data. Once you create the database it should be easy to read and write from it. Verify that you actually have a database created.
(2) Where are your SQL queries to return the data you're looking for? Even if data is being added you need to make sure you are getting the right data with your Cursor when you're done. If you're getting the same values each time is it possible that you are simply adding new data every time and retrieving the same value with your cursor - i.e. you're not telling the cursor to get the newly added data becuase you keep grabing the same index?
If you need to replace the data that's there you should be using update queries and not inserts.
I have two tables with names disease_table and sysmptoms_table. I retrieved the data from disease_table from the DB and displayed on the listview and when the listitem is clicked, I have to select and display disease category symptoms accordingly and I did that successfully but my code has redundancy, I had to write two methods in the datahelper class to retrieve the symptoms as per the disease in another listview. and I am retrieving the symptom data in list view with the query with the condition of WHERE "disease_id=1" with foreign key reference
the code for the methods is as follows,
//getting pain symptom names in a arraylist and then display in listview
//this.setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,symptompain));
public List<String> getAllSymptomPain() {
List<String> symptompain = null;
cr = db.query(SYMPTOM_TABLE_NAME, new String[] {"symname"}, "diseaseid=1", null, null, null, null);
if(null != cr){
symptompain = new ArrayList<String>();
if (cr.moveToFirst()) {
do {
symptompain.add(cr.getString(0));
} while (cr.moveToNext());
}
if (cr != null && !cr.isClosed()) {
cr.close();
}
}
return symptompain;
}
//getting colorchange symptom names in a arraylist and then display in listview
//this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,symptomcolorchange));
public List<String> getAllSymptomColorChange() {
List<String> symptomcolorchange = null;
cr = db.query(SYMPTOM_TABLE_NAME, new String[] {"symname"}, "diseaseid=2", null, null, null, null);
if(null != cr){
symptomcolorchange = new ArrayList<String>();
if (cr.moveToFirst()) {
do {
symptomcolorchange.add(cr.getString(0));
} while (cr.moveToNext());
}
if (cr != null && !cr.isClosed()) {
cr.close();
}
}
return symptomcolorchange;
}
How can I write these two in a single method and then call it in class which extends listactivity under onListItemclick method?
And my OnListItemClick() method is as follows :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String item=(String)getListAdapter().getItem(position);
if(item.equals("Pain in Teeth")){
// passing the method here
}
else if(item.equals("Pain in Gums")){
// passing the method here
}
else if(item.equals("Pain in Mucosa")){
// passing the method here
}
else if(item.equals("Pain in TMJoint")){
// passing the method here
}
else if(item.equals("Non-Specific Pain")){
// passing the method here
}
}
Try this:
public List<String> getSymptomsByDiseaseId(long diseaseId) {
List<String> symptomsList = new ArrayList<String>();
String selection = "diseaseid=?";
String[] selectionArgs = { String.valueOf(diseaseId) };
Cursor cursor = db.query(false, SYMPTOM_TABLE_NAME, null, selection, selectionArgs, null, null, null, null);
if (cursor.moveToFirst()) {
do {
symptomsList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
return symptomsList;
}