In my app I am fetching all the bookmarks available in the default browser and populating it in the list view . What i want is that when i click on a particular listItem(bookmark) , It should directly open that bookmark in the default browser .
String[] requestedColumns = { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.VISITS,
Browser.BookmarkColumns.BOOKMARK };
#SuppressWarnings("deprecation")
Cursor faves = managedQuery(Browser.BOOKMARKS_URI, requestedColumns,
Browser.BookmarkColumns.BOOKMARK + "=1", null,
Browser.BookmarkColumns.VISITS);
Log.d("Bookmarks", "Bookmarks count: " + faves.getCount());
int titleIdx = faves.getColumnIndex(Browser.BookmarkColumns.TITLE);
String url[] = new String[] {android.provider.Browser.BookmarkColumns.URL};
Log.d("SimpleBookmarks url", url[0]);
//int url_column_index = faves.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
faves.moveToFirst();
if (bookmark_check) {
while (!faves.isAfterLast()) {
Log.d("SimpleBookmarks", faves.getString(titleIdx));
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("bookmark", faves.getString(titleIdx));
map.put("url", "");
listitem.add(map);
faves.moveToNext();
}
}
Log.v("data", "" + listitem);
SimpleAdapter listitemAdapter = new SimpleAdapter(this, listitem,
R.layout.list_style, new String[] { "bookmark", "url" },
new int[] { R.id.topTextView, R.id.bottomTextView });
lv.setAdapter(listitemAdapter);
Finally got the solution .
String[] requestedColumns = { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
#SuppressWarnings("deprecation")
final Cursor faves = managedQuery(Browser.BOOKMARKS_URI,
requestedColumns, Browser.BookmarkColumns.BOOKMARK + "=1",
null, null);
faves.moveToFirst();
int titleIdx = faves.getColumnIndex(Browser.BookmarkColumns.TITLE);
final int urlIdx = faves.getColumnIndex(Browser.BookmarkColumns.URL);
if (bookmark_check) {
while (!faves.isAfterLast()) {
faves.getString(urlIdx));
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", faves.getString(titleIdx));
map.put("phone no", faves.getString(urlIdx));
listitem.add(map);
faves.moveToNext();
}
}
SimpleAdapter listitemAdapter = new SimpleAdapter(this, listitem,
R.layout.list_style, new String[] { "name", "phone no" },
new int[] { R.id.topTextView, R.id.bottomTextView });
lv.setAdapter(listitemAdapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
RelativeLayout lr = (RelativeLayout) arg1;
TextView mText = (TextView) lr.getChildAt(1);
String st = mText.getText().toString();
if (!st.startsWith("https://") && !st.startsWith("http://")) {
st = "http://" + mText.getText().toString();
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(st));
startActivity(i);
}
});
Related
When i run the following program:
ArrayList<HashMap<String, String>> AL = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_outaccountinfo);
ListView lv = (ListView) findViewById(R.id.lvoutinfo);
ArrayList<HashMap<String, String>> AL = new ArrayList<HashMap<String, String>>();
DBOpen open = new DBOpen(Outaccountinfo.this);
SQLiteDatabase db = open.getWritableDatabase();
Cursor cursor = db.query("outaccount", null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
String str_id = cursor.getString(cursor.getColumnIndex("id"));
String str_money = cursor.getString(cursor.getColumnIndex("outmoney"));
String str_time = cursor.getString(cursor.getColumnIndex("time"));
String str_type = cursor.getString(cursor.getColumnIndex("type"));
String str_mark = cursor.getString(cursor.getColumnIndex("mark"));
map.put("id", str_id);
map.put("outmoney", str_money);
map.put("time", str_time);
map.put("type", str_type);
map.put("mark", str_mark);
AL.add(map);
} while (cursor.moveToNext());
}
}
String[] str = new String[cursor.getCount()];
for (int i = 0; i < cursor.getCount(); i++) {
str[i] = AL.get(i).get("id").toString() + "|" + " " + "money:" + String.valueOf(AL.get(i).get("outmoney"))
+ " " + "time:" + AL.get(i).get("time").toString() + " " + "type:" + AL.get(i).get("type").toString()
+ " " + "mark:" + AL.get(i).get("mark").toString();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
str);
lv.setAdapter(arrayAdapter);
}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
HashMap<String, String> map = (HashMap<String, String>) parent.getItemAtPosition(position);
Toast.makeText(Outaccountinfo.this, map.get("type"), Toast.LENGTH_SHORT).show();
}
});
}
I receive the following error:
java.lang.String cannot be cast to java.util.HashMap
Who can help me to achieve the purpose without changing the purpose of the program?
Thanks!
You are using ArrayAdapter<String> Means that you pass your adapter object of Strings.
Now, when you clicked on your item and asked for parent.getItemAtPosition(position); you get an Object.
If you will go inside this function you can see that the Object that you get is by position and by the type you sent to the Adapter (String).
So, when you try to cast that String to (HashMap<String, String>) you get the exception.
Try to do something like that after you clicked:
HashMap<String, String> map = new HashMap<String, String>(); // Parameter in outside the click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
map.put("someKey", parent.getItemAtPosition(position));
Toast.makeText(Outaccountinfo.this, map.get("type"), Toast.LENGTH_SHORT).show();
}
});
*****Can you try this code It might be helpful.*****
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.lvoutinfo);
ArrayList<HashMap<String, String>> AL = new ArrayList<HashMap<String, String>>();
SQLiteDatabase db = openOrCreateDatabase("Account",MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXISTS outaccount(id text,outmoney text,time text,type text,mark text);");
db.execSQL("INSERT INTO outaccount VALUES('1','100','10','saving','80');");
Cursor cursor = db.query("outaccount", null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
String str_id = cursor.getString(cursor.getColumnIndex("id"));
String str_money = cursor.getString(cursor.getColumnIndex("outmoney"));
String str_time = cursor.getString(cursor.getColumnIndex("time"));
String str_type = cursor.getString(cursor.getColumnIndex("type"));
String str_mark = cursor.getString(cursor.getColumnIndex("mark"));
map.put("id", str_id);
map.put("outmoney", str_money);
map.put("time", str_time);
map.put("type", str_type);
map.put("mark", str_mark);
AL.add(map);
} while (cursor.moveToNext());
}
}
String[] str = new String[cursor.getCount()];
for (int i = 0; i < cursor.getCount(); i++) {
str[i] = AL.get(i).get("id").toString() + "|" + " " + "money:" + String.valueOf(AL.get(i).get("outmoney"))
+ " " + "time:" + AL.get(i).get("time").toString() + " " + "type:" + AL.get(i).get("type").toString()
+ " " + "mark:" + AL.get(i).get("mark").toString();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
str);
lv.setAdapter(arrayAdapter);
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
HashMap<String, String> map = (HashMap<String, String>) parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this, map.get("type"), Toast.LENGTH_SHORT).show();
}
});
}
}
I am populating spinner from below code and its working perfect. When user select any value from spinner then I am saving stateCodeId in sqlite. Now what I want that when user come again then I want to show the seleted value from ID which already saved in sqlite. How can I show value selected in spinner ?
public void fillStateData() {
try {
State_data = new ArrayList<Map<String, String>>();
State_data.clear();
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
int i = 0;
if (cursor_State.moveToFirst()) {
do {
Map<String, String> datanum = new HashMap<String, String>();
if (i == 0) {
datanum.put("nStateID", "0");
datanum.put("cStateName", "Select State");
State_data.add(datanum);
datanum = new HashMap<String, String>();
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
} else {
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
}
i += 1;
} while (cursor_State.moveToNext());
}
String[] fromwhere = {"nStateID", "cStateName"};
int[] viewswhere = {R.id.txtnStateID, R.id.txtcStateName};
StateAdapter = new SimpleAdapter(getActivity(), State_data, R.layout.state_list_template, fromwhere, viewswhere);
spnState.setAdapter(StateAdapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView stateId = (TextView) view.findViewById(R.id.txtnStateID);
stateCodeId = stateId.getText().toString();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Like this I am getting ID from sqlite.
Cursor c = db.rawQuery("SELECT nStateId from MemberMaster where nCustID ="+SesPMbrID+"", null);
c.moveToFirst();
String state = c.getString(0);
Use
spinner.setSelection(position);
My listView works well when only 1 item added to the listview at one time. But when multiple item is added, listener in listview is not wokring. Can anyone guide me what i am doing wrong here? Thanks.
Here is my listView code:
public class Participant extends ListFragment implements OnClickListener{
Intent intent;
TextView friendId;
Button addparticipant;
String eventId;
ListView lv;
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
ArrayList<HashMap<String, String>> friendList = controller
.getAllFriends(queryValues);
if (friendList.size() != 0) {
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
friendId = (TextView) view.findViewById(R.id.friendId);
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EventPage.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
friendId = (TextView) arg1.findViewById(R.id.friendId);
registerForContextMenu(getListView());
return false;
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
friendList, R.layout.view_friend_entry, new String[] {
"friendId", "friendName", "friendSpending" },
new int[] { R.id.friendId, R.id.friendName,
R.id.friendSpending });
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.participant, container, false);
addparticipant = (Button) rootView.findViewById(R.id.addpart);
addparticipant.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getActivity(),
AddParticipant.class);
objIntent.putExtra("eventId", eventId);
startActivity(objIntent);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
String[] menuItems = getResources().getStringArray(R.array.menu);
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int menuItemIndex = item.getItemId();
EventController controller = new EventController(getActivity());
switch (menuItemIndex) {
case 0:
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EditParticipant.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
break;
case 1:
String valFriendId2 = friendId.getText().toString();
controller.deleteFriend(valFriendId2);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(UpdateReceiver.NEW_UPDATE_BROADCAST);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
getActivity().sendBroadcast(broadcastIntent);
onResume();
}
return true;
}
#Override
public void onResume() {
super.onResume();
if (getListView() != null) {
updateData();
}
}
private void updateData() {
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
controller.getAllFriends(queryValues),
R.layout.view_friend_entry, new String[] { "friendId",
"friendName", "friendSpending" }, new int[] {
R.id.friendId, R.id.friendName, R.id.friendSpending });
setListAdapter(adapter);
}
Here i add item to listView:
public class AddParticipant extends Activity implements OnClickListener {
private static final int REQUEST_CODE_PICK_CONTACTS = 1;
private static final String TAG = AddParticipant.class.getSimpleName();
private Uri uriContact;
private String contactID;
EditText friendName;
EditText friendNumber;
EditText friendEmail;
EventController controller = new EventController(this);
Button btnadd;
Button addcontact;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addparticipant);
friendName = (EditText) findViewById(R.id.friendName);
friendNumber = (EditText) findViewById(R.id.friendNumber);
friendEmail = (EditText) findViewById(R.id.friendEmail);
btnadd = (Button) findViewById(R.id.saveButton);
btnadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getIntent();
String eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
queryValues.put("friendName", friendName.getText().toString());
queryValues.put("friendNumber", friendNumber.getText()
.toString());
queryValues
.put("friendEmail", friendEmail.getText().toString());
controller.insertFriend(queryValues);
callHomeActivity(v);
finish();
}
});
addcontact = (Button) findViewById(R.id.fromcontact);
addcontact.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivityForResult(new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI),
REQUEST_CODE_PICK_CONTACTS);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_CONTACTS
&& resultCode == RESULT_OK) {
Log.d(TAG, "Response: " + data.toString());
uriContact = data.getData();
retrieveContactName();
retrieveContactNumber();
retrieveContactEmail();
}
}
private void retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getContentResolver().query(uriContact,
new String[] { ContactsContract.Contacts._ID }, null, null,
null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID
.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
Log.d(TAG, "Contact ID: " + contactID);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER },
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND "
+ ContactsContract.CommonDataKinds.Phone.TYPE + " = "
+ ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[] { contactID }, null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone
.getString(cursorPhone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
friendNumber.setText(contactNumber);
}
private void retrieveContactName() {
String contactName = null;
// querying contact data store
Cursor cursor = getContentResolver().query(uriContact, null, null,
null, null);
if (cursor.moveToFirst()) {
// DISPLAY_NAME = The display name for the contact.
// HAS_PHONE_NUMBER = An indicator of whether this contact has at
// least one phone number.
contactName = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
Log.d(TAG, "Contact Name: " + contactName);
friendName.setText(contactName);
}
private void retrieveContactEmail() {
ContentResolver contactResolver = this.getContentResolver();
Cursor emailCursor = contactResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[] { contactID }, null);
while (emailCursor.moveToNext()) {
String phone = emailCursor
.getString(emailCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCursor
.getInt(emailCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email
.getTypeLabel(this.getResources(), type, "");
Log.d("TAG", s + " email: " + phone);
friendEmail.setText(phone);
}
emailCursor.close();
}
public void callHomeActivity(View view) {
super.onResume();
}
You have write custom adapter for multiple items
http://www.javacodegeeks.com/2013/09/android-listview-with-adapter-example.html
I have a ListView in which there are 20 items . 10 items are contacts of my phone and rest of the 10 are bookmars url of my default browser . What i want is that:
1) when i click on the contacts(first 10) it should take me to that partular contact in contact app.
2)when i click on the bookmark url(rest of the 10) , it should open that url in the browser .
I implemented the first requirement of mine with the following code below :
ArrayList<HashMap<String, Object>> listitem = new ArrayList<HashMap<String, Object>>();
mSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
Boolean contact_check = mSharedPrefs.getBoolean("contact_check", true);
Boolean bookmark_check = mSharedPrefs
.getBoolean("bookmark_check", true);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (contact_check) {
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
while (pCur.moveToNext()) {
String phoneNo = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", name);
map.put("phone no", phoneNo);
// map.put("Bookmarks", faves.getString(titleIdx));
listitem.add(map);
}
pCur.close();
}
}
}
}
SimpleAdapter listitemAdapter = new SimpleAdapter(this, listitem,
R.layout.list_style, new String[] { "name", "phone no" },
new int[] { R.id.topTextView, R.id.bottomTextView });
lv.setAdapter(listitemAdapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
RelativeLayout lr = (RelativeLayout) arg1;
TextView mText = (TextView) lr.getChildAt(1);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setAction(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT);
i.setData(Uri
.fromParts("tel", mText.getText().toString(), null));
startActivity(i);
}
});
The above code is adding the contacts in my listview on handling the click event .
For my second requirement i extended my listview with bookmarks , with the following code:
String[] requestedColumns = { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
#SuppressWarnings("deprecation")
final Cursor faves = managedQuery(Browser.BOOKMARKS_URI, requestedColumns,
Browser.BookmarkColumns.BOOKMARK + "=1", null, null);
Log.d("Bookmarks", "Bookmarks count: " + faves.getCount());
faves.moveToFirst();
int titleIdx = faves.getColumnIndex(Browser.BookmarkColumns.TITLE);
final int urlIdx = faves.getColumnIndex(Browser.BookmarkColumns.URL);
if (bookmark_check) {
while (!faves.isAfterLast()) {
Log.d("SimpleBookmarks", faves.getString(titleIdx));
Log.d("SimpleBookmarks url", " " + faves.getString(urlIdx));
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", faves.getString(titleIdx));
map.put("phone no", faves.getString(urlIdx));
listitem.add(map);
faves.moveToNext();
}
Its getting populated but i am not able to handle its click event . I want to open the url in the browser when the user click on it.
with some adaptation to your method:
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
if (arg2 < 10)
{
RelativeLayout lr = (RelativeLayout) arg1;
TextView mText = (TextView) lr.getChildAt(1);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setAction(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT);
i.setData(Uri.fromParts("tel", mText.getText().toString(), null));
startActivity(i);
}
else
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getCurrentUri));
//getCurrentUri is the uri at position arg2-10
startActivity(browserIntent);
}
}
});
This Code shows the List of Contact Numbers, but i want to select cell number from selected contact display name--->
Cursor cursor= managedQuery(intent.getData(), null, null, null, null);
while(cursor.moveToNext()) {
String contactId=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
System.out.println("---------ContactId---------"+contactId);
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("---------NAME---------"+name);
String hasPhone=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
System.out.println("---------HAS Phone---------"+hasPhone);
ArrayList one= new ArrayList();
ArrayList two= new ArrayList();
// if(Boolean.parseBoolean(hasPhone)) {
Cursor phones=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = "+ contactId, null, null);
while(phones.moveToNext()) {
phoneNumber= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("---------Number---------"+phoneNumber);
one.add(phoneNumber);
System.out.println("---------email Address---------"+one);
} phones.close();
// }
Display Names
public class ContentProviderActivity extends Activity {
ListView lv;
Map<String, List<String>> mymap;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listContact);
mymap = new HashMap<String, List<String>>();
Uri allContacts = Uri.parse("content://contacts/people/");
Cursor mCursor = managedQuery(allContacts, null, null, null, ContactsContract.Contacts._ID + " ASC");
final String[] contacts = new String[]{ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID};
int [] view = new int[]{R.id.txtName,R.id.txtID};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.main, mCursor, contacts, view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
//displayContacts(position+1);
int id1 = (int) adapter.getItemId(position);
Intent i = new Intent(getApplicationContext(),ShowContactNo.class);
i.putExtra("ID", id1);
startActivity(i);
}
});
}
}
ShowContactNo: TO display associated contact numbers
public class ShowContactNo extends ListActivity{
Map<String, List<String>> mymap;
String name;
List<String> Phone_No;
String select_Number;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mymap = new HashMap<String, List<String>>();
ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_NONE);
Intent i = getIntent();
int position = i.getIntExtra("ID", 0);
displayContacts(position);
Phone_No = new ArrayList<String>();
Phone_No = mymap.get(name);
System.out.println(Phone_No);
if(Phone_No!=null)
{
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, Phone_No));
}
final String [] items = new String [] {"Make Call", "Send Text SMS"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
if (item == 0) {
Intent i = new
Intent(android.content.Intent.ACTION_CALL,
Uri.parse("tel:"+select_Number));
startActivity(i);
dialog.cancel();
} else {
Intent i = new
Intent(android.content.Intent.ACTION_SENDTO,
Uri.parse("smsto:"+select_Number));
i.putExtra("sms_body", "Krishnakant Dalal");
startActivity(i);
}
}
} );
final AlertDialog dialog = builder.create();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
select_Number = String.valueOf(Phone_No.get(arg2));
dialog.show();
}
});
}
private void displayContacts(int position) {
if(position!=0)
{
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, ContactsContract.Contacts._ID +" = ?",
new String[]{String.valueOf(position)}, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
List<String> numberlist = new ArrayList<String>();
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Toast.makeText(this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
numberlist.add(phoneNo);
}
pCur.close();
mymap.put(name, numberlist);
}
}
}
}
}
}
Dont forget to add Permissions:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
Try this,
public void getPhoneNumber(String conatctname)
{
try
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
FirstName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if(FirstName!=null)
{
try
{
String[] splitval=FirstName.split(" ");
if(splitval.length>=1)
{
FirstName=splitval[0];
if(FirstName.equals(conatctname))
{
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
PhoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
PhoneNumberArray.add(PhoneNumber);
}
pCur.close();
}
}
}
catch(Exception error)
{
Log.d("SplitError", error.getMessage());
}
}
cursor.close();
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
}