I want to get the Contact name of the selected contact in android while working with default contacts of phone.
I tried like this but it show all the contact names in the phone but i want only selected contact name
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phNumber));
// query time
Cursor cursor = this.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.v("sai", "Started uploadcontactphoto: Contact Found # " + phNumber);
Log.v("sai", "Started uploadcontactphoto: Contact name = " + name);
} else {
Log.v("sai", "Contact Not Found # " + phNumber);
}
cursor.close();
}
So, you're using the right approach, but you aren't telling Android what specific contact to look up.
You don't state what a "selected contact" is, but I assume you should know its phone number or some such by which to actually query the contact list.
According to documentation, you're just not using the selection parameters.
You can write selection param just as you would an SQL query's WHERE statement. As in
ContactsContract.PhoneLookup + " = 123456789"
See this answer for a more detailed explanation.
Here is the code in which i am storing the email address and contact person name in arraylist
public ArrayList<ContactVo> getNameEmailDetails() {
ArrayList<ContactVo> m_arrList = new ArrayList<ContactVo>();
ArrayList<String> emlRecs = new ArrayList<String>();
HashSet<String> emlRecsHS = new HashSet<String>();
ContentResolver cr = m_context.getContentResolver();
String[] PROJECTION = new String[] { ContactsContract.RawContacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_ID,
ContactsContract.CommonDataKinds.Email.DATA,
ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
String order = "CASE WHEN " + ContactsContract.Contacts.DISPLAY_NAME
+ " NOT LIKE '%#%' THEN 1 ELSE 2 END, "
+ ContactsContract.Contacts.DISPLAY_NAME + ", "
+ ContactsContract.CommonDataKinds.Email.DATA
+ " COLLATE NOCASE";
String filter = ContactsContract.CommonDataKinds.Email.DATA
+ " NOT LIKE ''";
Cursor cur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION,
filter, null, order);
ContactVo m_vo;
if (cur.moveToFirst()) {
do {
m_vo = new ContactVo();
// names comes in hand sometimes
String name = cur.getString(1);
String emlAddr = cur.getString(3);
System.err.println("Value Is---------->" + cur.getString(2)
+ "Name--" + name + "Email---" + emlAddr);
m_vo.setM_sName(name);
m_vo.setM_sEmail(emlAddr);
// keep unique only
if (emlRecsHS.add(emlAddr.toLowerCase())) {
emlRecs.add(emlAddr);
}
m_arrList.add(m_vo);
} while (cur.moveToNext());
}
cur.close();
return m_arrList;
}
EDITED:
Write the below code in your onItemClick event of your listview where you are showing all the contact list.
m_lvList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(m_context, m_arrContact.get(arg2).getM_sEmail(), Toast.LENGTH_LONG).show();
Intent in = new Intent(m_context, Test.class);
in.putExtra("pos", arg2);
in.putParcelableArrayListExtra("parcel", m_arrContact);
startActivity(in);
}
});
Make your vo parcelable to pass the details into another activity and access it.
ContactVo
public class ContactVo implements Parcelable {
private String m_sName, m_sEmail;
public ContactVo() {
}
public ContactVo(Parcel in) {
readFromParcel(in);
}
public String getM_sName() {
return m_sName;
}
public void setM_sName(String m_sName) {
this.m_sName = m_sName;
}
public String getM_sEmail() {
return m_sEmail;
}
public void setM_sEmail(String m_sEmail) {
this.m_sEmail = m_sEmail;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(m_sName);
dest.writeString(m_sEmail);
}
public void readFromParcel(Parcel p_in) {
m_sName = p_in.readString();
m_sEmail = p_in.readString();
}
public static final Parcelable.Creator<ContactVo> CREATOR = new Parcelable.Creator<ContactVo>() {
public ContactVo createFromParcel(Parcel s) {
return new ContactVo(s);
}
public ContactVo[] newArray(int size) {
return new ContactVo[size];
}
};
}
In your another activity write as below:
public class Test extends Activity {
ArrayList<ContactVo> m_arr;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
m_arr = getIntent().getParcelableArrayListExtra("parcel");
int pos = getIntent().getIntExtra("pos", 0);
System.out.println("Detailsss------>" + m_arr.get(pos).getM_sEmail()
+ m_arr.get(pos).getM_sName());
}
}
You can add as many details as much you want into the ArrayList<ContactVo> and pass it into another activity.
To get other contact details Check out HERE
Related
I'm showing contacts in a ListView and trying to filter the same list using an EditText. But when I type something, filtering is not happening, though the typed text is coming in Logcat.
Here is my onCreate:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_invite);
EditText filterText = findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[]{"_id", "name", "details"});
// Adapter to set data in the listview
mAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.contact_layout, null, new String[]{"name", "details"}, new int[]{R.id.tv_name, R.id.tv_details}, 0);
// Getting reference to listview
ListView lstContacts = findViewById(R.id.lst_contacts);
// Setting the adapter to listview
lstContacts.setAdapter(mAdapter);
// Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
}
This is my TextWatcher:
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.d(TAG, "onTextChanged: " + s);
mAdapter.getFilter().filter(s.toString());
}
};
What am I doing wrong here? Can someone help?
EDIT: Adding my ListViewContactsLoader.
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor> {
#Override
protected Cursor doInBackground(Void... params) {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri,
null, null, null,
ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
if (contactsCursor.moveToFirst()) {
do {
long contactId = contactsCursor.getLong(contactsCursor
.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone etc corresponding to each contact
Cursor dataCursor = getContentResolver().query(dataUri,
null,
ContactsContract.Data.CONTACT_ID + "=" + contactId,
null, null);
String displayName = "";
String mobilePhone = "";
if (dataCursor.moveToFirst()) {
// Getting Display Name
displayName = dataCursor
.getString(dataCursor
.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
do {
// Getting Phone numbers
if (dataCursor
.getString(
dataCursor
.getColumnIndex("mimetype"))
.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
switch (dataCursor.getInt(dataCursor
.getColumnIndex("data2"))) {
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
mobilePhone = dataCursor
.getString(dataCursor
.getColumnIndex("data1"));
break;
}
}
} while (dataCursor.moveToNext());
String details = "";
// Concatenating various information to single string
if (mobilePhone != null && !mobilePhone.equals(""))
details = mobilePhone + "\n";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{
Long.toString(contactId), displayName, details});
}
} while (contactsCursor.moveToNext());
}
return mMatrixCursor;
}
#Override
protected void onPostExecute(Cursor result) {
// Setting the cursor containing contacts to listview
mAdapter.swapCursor(result);
Log.d(TAG, "onPostExecute: " + result);
}
}
You need to reset the ListViewadapter also after adding the text in EditText.
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text [" + s + "] - Start [" + start + "] - Before [" + before + "] - Count [" + count + "]");
if (count < before) {
listAdapter.resetData(); // MARK: Resetting adapter here
}
listAdapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
Note: resetData() is custom method in which you have to replace the List data with new List Data that appears after applying the Filter. Then finally notify the Adapter.
I am new to android programming. I am having a little issue on how to retrieve a single record while using Inner joins. From research I know how to do it with one table e.g
public Shop getShop(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_SHOPS, new String[] { KEY_ID,
KEY_NAME, KEY_SH_ADDR }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Shop contact = new Shop(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return shop
return contact;
}
But I am at a loss when I have to consider three different tables. I have been able to retrieve all records, currently my code to retreive a single record is below. I have been able to replace ? with a corresponding id and it works but I obviously do not want to have that static.
getTeam method
//Getting Single Team
public List < Team > getTeam() {
List < Team > teamList = new ArrayList < Team > ();
// Select All Query
String selectQuery = "SELECT teams.id, teams.team_name, teams.image, teams_vs_leagues.points, leagues.league_name " +
"FROM teams_vs_leagues " +
"INNER JOIN teams " +
"ON teams_vs_leagues.team_id = teams.id " +
"INNER JOIN leagues " +
"ON teams_vs_leagues.league_id = leagues.id " +
"WHERE teams.id = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Team team = new Team();
team.setId(Integer.parseInt(cursor.getString(0)));
team.setTeamName(cursor.getString(1));
team.setPath(cursor.getString(2));
team.setPoints(Integer.parseInt(cursor.getString(3)));
team.setLeagueName(cursor.getString(4));
// Adding team to list
teamList.add(team);
} while (cursor.moveToNext());
}
// close inserting data from database
db.close();
// return team list
return teamList;
}
Team class
public class Team {
String team_name, path, league_name;
int id, league_id, points;
public Team(int keyId, String team_name, String path,
int points, String league_name) {
this.id = keyId;
this.team_name = team_name;
this.path = path;
this.points = points;
this.league_name = league_name;
}
public Team() {}
public Team(int keyId) {
this.id = keyId;
}
public int getId() {
return id;
}
public void setId(int keyId) {
this.id = keyId;
}
public int getLeagueId() {
return league_id;
}
public String getTeamName() {
return team_name;
}
public String getLeagueName() {
return league_name;
}
public void setLeagueName(String league_name) {
this.league_name = league_name;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public void setTeamName(String team_name) {
this.team_name = team_name;
}
public void setLeague_id(int league_id) {
this.league_id = league_id;
}
public void setPath(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
Since you are using placeholder
"WHERE teams.id = ?";
in your query , you need to pass selection arguments in rawQuery() so that during the execution of your query , the placeholder will be replaced by the actual value.
Cursor cursor = db.rawQuery(selectQuery, new String[]{id});//"id" is the value which you want to pass in place of "?". You can hardcode it or you can pass it all the way to getTeam()
Check this .
I have created a database in sqlite for android with variables like Acc No, name, date etc etc.
i have many edit text in my activity. when the acc no is entered in Acc No edit text, the corresponding name should appear in below Name edit text. how to do that.
my DB code is given below
public void getName(Editable account_edit_txt){
"Acc_No " + account_edit_txt, null, null, null, null);
Cursor cursor = db.query(DATABASE_TABLE, new String[] {"Cust_Name","Acc_No"}, "Acc_No=?",new String[]{"account_edit_txt"}, null, null, null);
Log.e("running", "cursor run");
if(cursor!=null)
{
Log.e("running", "curosr is not null");
while(cursor.isFirst())
{
Log.e("running", "cursor while loop enter");
String temp = (cursor.getString(cursor.getColumnIndex("Cust_Name")));
String temp2 =(cursor.getString(cursor.getColumnIndex("Acc_No")));
Log.e("running", "id acc num" +temp+ " name"+temp2);
}
}
Activity code is given below
public class TransactionActivity extends Activity {
EditText acc_edit;
TextView acc_txt;
Editable account_edit_txt;
Connection connection;
String name;
SQLiteDatabase sdb;
AccountDBAdapter db = new AccountDBAdapter(this);
//
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.transaction_page);
acc_edit = (EditText) findViewById(R.id.edittext_Acc_No);
acc_txt = (TextView) findViewById(R.id.text_show_name);
final String editable = String.valueOf(acc_edit.getText());
Log.e("editable value", "" + account_edit_txt);
acc_edit.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int count,
int after) {
if (start >= 2) {
db.open();
account_edit_txt = acc_edit.getText();
db.getName(account_edit_txt);
db.close();
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
}
Below function will help you to retrieve account holder name for given account number.
Non need to fecth Acc_No again. Ad you are already have account number which user has inserted.
Also assuming that there will be only one record associated with the give account number.
public String getAccountHolderName(String accountNumber) {
String accountHolderName = null;
Cursor cursor = db.query(DATABASE_TABLE, new String[] { "Cust_Name" },
"Acc_No=?", new String[] { accountNumber }, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
accountHolderName = (cursor.getString(cursor
.getColumnIndex("Cust_Name")));
cursor.close();
}
return accountHolderName;
}
I want user to select a number from calllog and that number get selected and come in the activity. So I created custom calllog list. I used this code but it is not showing the call log list in right order
first thing it is showing the callhistory of the first number fully that it gets in the calllog list
second I wnt to show the name also, I tried a lot but I am not able to do
Can anyone tell what amendments i make in this code to make it right
The code I used is:
String[] callLogFields = { android.provider.CallLog.Calls._ID,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.CACHED_NAME };
String viaOrder = android.provider.CallLog.Calls.DATE + " DESC";
String WHERE = android.provider.CallLog.Calls.NUMBER + " >0"; /*filter out private/unknown numbers */
final Cursor callLog_cursor = this.getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, callLogFields,
WHERE, null, viaOrder);
AlertDialog.Builder myversionOfCallLog = new AlertDialog.Builder(this);
android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
callLog_cursor.moveToPosition(item);
Log.v("number", callLog_cursor.getString(callLog_cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER)));
callLog_cursor.close();
}
};
myversionOfCallLog.setCursor(callLog_cursor, listener,
android.provider.CallLog.Calls.NUMBER);
myversionOfCallLog.setTitle("Choose from Call Log");
myversionOfCallLog.create().show();
You can add the Contact Numbers in a Set, which will prevent adding duplicate contact numbers. Then add the Set's data to listview as you want.
Set<String> setNumbers = new HashSet<String>();
String callNumber = cursor.getString(cursor.getColumnIndex(
android.provider.CallLog.Calls.NUMBER));
setNumbers.add(callNumber);
Hope this helps.
For saving numbers without duplicates, as MysticMagic suggested, use 'Set' as per the link given in the comment.
For getting the contact name from the phone number, use code :
(Reference)
private String getContactName(Context context, String number) {
String name = null;
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID};
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.v(TAG, "Started uploadcontactphoto: Contact Found # " + number);
Log.v(TAG, "Started uploadcontactphoto: Contact name = " + name);
} else {
Log.v(TAG, "Contact Not Found # " + number);
}
cursor.close();
}
return name;
}
Also refer here for another method to fetch name in phone call history
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
String num= c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));// for number
String name= c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));// for name
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out going
Finally this is the code that worked with the help of MysticMagic and Nishanthi Grashia
Set setA;
setA = new HashSet();
public void getCallLog() {
try {
final String[] projection = null;
final String selection = null;
final String[] selectionArgs = null;
final String sortOrder = "DATE DESC";
final Cursor cursor = this.getContentResolver().query(
Uri.parse("content://call_log/calls"), projection,
selection, selectionArgs, sortOrder);
if (cursor != null) {
// Loop through the call log.
while (cursor.moveToNext()) {
// Common Call Log Items
String callNumber = cursor
.getString(cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
setA.add(callNumber);
}
generateList();
}
} catch (Exception e) {
}
}
#SuppressLint("NewApi")
private void generateList() {
// TODO Auto-generated method stub
try {
Object[] calllist = new String[setA.size()];
calllist = setA.toArray();
String scalllist[] = Arrays.copyOf(calllist, calllist.length,
String[].class);
for (int i = 0; i < scalllist.length; i++) {
scalllist[i] = scalllist[i] + " "
+ getContactName(this, scalllist[i]);
}
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog1);
d.setTitle("Choose from Call Log...");
final ListView lv1 = (ListView) d.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
scalllist);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String clickednumber[] = (lv1.getItemAtPosition(arg2)
.toString()).split(" ");
usernumber.setText(clickednumber[0]);
try {
username.setText(clickednumber[1]);
} catch (ArrayIndexOutOfBoundsException e) {
username.setText(" ");
}
d.dismiss();
}
});
d.show();
} catch (Exception e) {
}
}
private String getContactName(Context context, String number) {
String name = null;
try {
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID };
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri,
projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
} else {
name = " ";
}
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return name;
}
I am attempting to delete a record from my database,
Short Summary:
My database populates a listview
The user can click the listview and
view more details on a new activity
I want to able to delete the
record from this new activity
CODE
I have a class named ModuleDatabaseHandler that manages the database. In this, I have a method called getData() that populates records to a ListView in ActivityViewAll:
ModuleDatabaseHandler
public ArrayList<String> getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_MODULE_CODE,
KEY_MODULE_NAME, KEY_LECTURE_PRACTICAL,
KEY_LECTURE_PRACTICAL_SHORT, KEY_LECTURE_DAY,
KEY_LECTURE_DAY_SHORT, KEY_START_TIME, KEY_END_TIME,
KEY_LOCATION, ADDITIONAL_INFO };
Cursor c = ourDatabase.query(DATABASE_MODULES, columns, null, null,
null, null, null);
ArrayList<String> results = new ArrayList<String>();
int indexModCode = c.getColumnIndex(KEY_MODULE_CODE);
int indexLectPracShort = c.getColumnIndex(KEY_LECTURE_PRACTICAL_SHORT);
int indexLectDayShort = c.getColumnIndex(KEY_LECTURE_DAY_SHORT);
int indexLectStart = c.getColumnIndex(KEY_START_TIME);
int indexLectLoc = c.getColumnIndex(KEY_LOCATION);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results.add(c.getString(indexModCode) + " "
+ c.getString(indexLectPracShort) + " "
+ c.getString(indexLectDayShort) + " "
+ c.getString(indexLectStart) + " "
+ c.getString(indexLectLoc));
}
return results;
}
This data is read in by ActivityViewAll:
ActivityViewAll
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_modules_test);
ModuleDatabaseHandler info = new ModuleDatabaseHandler(this);
info.open();
ArrayList<String> data = info.getData();
info.close();
l = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
l.setAdapter(adapter);
l.setOnItemClickListener(this);
}
I have another method in the ModuleDatabaseHandler class called getAllData() that allows the user to press a ListView item and read full details about the item on a new activity, ActivityFullDetails:
public String getAllData(int specified_position) {
// TODO Auto-generated method stub
int position = specified_position;
if(c.moveToPosition(specified_position)) {
String result = "";
for(int columnIndex = 0; columnIndex<c.getColumnCount();columnIndex++) {
result += c.getString(columnIndex)+" ";
}
return result;
} else {
throw new IllegalArgumentException("Row " + specified_position + " does not exist");
}
}
The data is transfered from the listView in ActivityViewAll to ActivityFullDetails using onItemClick:
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView temp = (TextView) view;
Toast.makeText(this, temp.getText() + " " + i, Toast.LENGTH_SHORT)
.show();
ModuleDatabaseHandler info = new ModuleDatabaseHandler(this);
info.open();
String module_info = info.getAllData(i);
info.close();
Intent fullModuleDetails = new Intent();
fullModuleDetails.setClassName("com.example.collegetimetable",
"com.example.collegetimetable.ModuleDetails");
fullModuleDetails.putExtra("list1", module_info);
startActivity(fullModuleDetails);
}
Back in the ModuleDatabaseHandler class, I created a method called deleteEntry to attempt to delete a row:
public void deleteEntry(long row){
ourDatabase.delete(DATABASE_MODULES, KEY_ROWID + "=" + row, null);
}
The Problem
How can I pass the ROW_ID from the ModuleDatabaseHandler class to the listView in ActivityViewAll and then to the ActivityFullDetails so I can delete the record?
SOLVED
Thanks to Serge who helped me solve this, by creating a getRowId method as seen in the accepted answer. Although I did have to add a cursor query within the method which is not shown in the accepted answer i.e.:
public int getRowID(int specified_position) {
String[] columns = new String[]{ KEY_ROWID, KEY_MODULE_CODE, KEY_MODULE_NAME, KEY_LECTURE_PRACTICAL, KEY_LECTURE_DAY, KEY_START_TIME,KEY_END_TIME, KEY_LOCATION, ADDITIONAL_INFO};
Cursor c = ourDatabase.query(DATABASE_MODULES, columns, null, null, null, null, null);
// rest of method as shown below
}
This method is called in the ActivityViewAll activity page from an instance of ModuleDatabaseHandler class, passed to the ActivityFullDetails page using putExtra,(and received using getIntent().getExtras as usual)..the delete method can then use the rowid.
Add function
public int getRowID(int specified_position) {
int position = specified_position;
if(c.moveToPosition(specified_position)) {
return c.getInteger(c.getColumnIndex(KEY_ROWID));
} else {
throw new IllegalArgumentException("Row " + specified_position + " does not exist");
}
}
And then to get it use
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView temp = (TextView) view;
Toast.makeText(this, temp.getText() + " " + i, Toast.LENGTH_SHORT)
.show();
ModuleDatabaseHandler info = new ModuleDatabaseHandler(this);
info.open();
String module_info = info.getAllData(i);
int rowID = info.getRowID(i);
info.close();
Intent fullModuleDetails = new Intent();
fullModuleDetails.setClassName("com.example.collegetimetable",
"com.example.collegetimetable.ModuleDetails");
fullModuleDetails.putExtra("list1", module_info);
fullModuleDetails.putExtra("rowid", rowID);
startActivity(fullModuleDetails);
}