Android: How to insert a call button in a Listview - android

PrintScreen
I have a listView with 3 Views
1) ImageView
2) TextView
3) Button
What I want to make is that when I click on a button, it gets triggered and call to the specific person.
Telephone numbers are stored in strings.xml file as
<string-array name="telePhoneNummber">
<item>123</item>
<item>8765</item>
<item>565767</item>
</string-array>
And here is my Adapter Class.
public class MoviesAdapter extends ArrayAdapter {
List list = new ArrayList();
public MoviesAdapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler {
ImageView Poster;
TextView title;
Button telePhone;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row_layout, parent, false);
handler = new DataHandler();
handler.Poster = (ImageView) row.findViewById(R.id.movie_poster);
handler.title = (TextView) row.findViewById(R.id.movie_title);
handler.telePhone = (Button) row.findViewById(R.id.btn_call);
row.setTag(handler);
} else {
handler = (DataHandler) row.getTag();
}
MovieDataProvider dataProvider;
dataProvider = (MovieDataProvider) this.getItem(position);
handler.Poster.setImageResource(dataProvider.getMovie_poster_resource());
handler.title.setText(dataProvider.getMovie_title());
handler.telePhone.setText(dataProvider.getTelePhone());
return row;
}
}
Don't pay attention on the naming convention please.

In your getView() method, simply add an onClickListener() to the appropriate button resource...
handler.telePhone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Intent to launch phone dialer
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + dataProvider.getTelePhone().trim()));
context.startActivity(intent);
}
});
EDIT 1: not sure whether the NullPointerException in your onClickListener occurs on line 82 or 83 of your adapter class but you probably need to pass context to it. Add the following to your current code:
Below List list = new ArrayList(); add Context context;
Change your constructor to:
public MoviesAdapter(Context context, int resource) {
super(context, resource);
this.context = context;
}
And see if it solves the problem.
EDIT 2: Or, leave your original code untouched and in the onClickListener, change context.startActivity(intent); to initActivity(intent); for which you'll need to add the following method:
private void initActivity(Intent intent) {
this.getContext().startActivity(intent);
}

Write your Listview on click listener and open the phone Dialer like this:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String[] numberArray= context.getResources().getStringArray(R.array.telePhoneNummber); // get array from strings.xml
// launch dialer with pre-filled phone number
Intent phoneDialerIntent= new Intent(Intent.ACTION_DIAL);
phoneDialerIntent.setData(Uri.parse("tel:" + numberArray[position]));
startActivity(phoneDialerIntent);
}
});

Related

Adding another image from database url to Android studio list view

I have a working list view with images from the drawables folder, I have working code which takes an image and uploads it to my server etc, I have the url to fetch the image from the database and I now am stuck in how to add it into my already existing list View by automatically adding a new image from this link into the list view.
This is the 'timeline' list view which displays the pictures we already have
/**
* Method which creates the list view on screen and displays images
*/
public class Timeline extends Activity implements OnItemClickListener {
//global variables
String[] pic_names;
TypedArray profile_pics;
List<RowItem> rowItems;
ListView mylistview;
ImageView btnTakePic;
String[] uploaded_pic_name;
TypedArray pic_url;
//Overridden method to create the main layout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timeline);
//set the global variables
//rowItems is now an arraylist
rowItems = new ArrayList<RowItem>();
//pic_names is set to the resource of pic_names
pic_names = getResources().getStringArray(R.array.pic_names);
uploaded_pic_name = getResources().getStringArray(R.array.uploaded_pic_name);
pic_url = getResources().obtainTypedArray(R.array.pic_url);
//profile_pics is now set to the resource of profile_pics
profile_pics = getResources().obtainTypedArray(R.array.profile_pics);
//gets the picture and name for each resource in the for loop array
for (int i = 0; i < pic_names.length; i++) {
RowItem item = new RowItem(pic_names[i], profile_pics.getResourceId(i, -1));
//adds items from the array
rowItems.add(item);
}
RowItem uploadedItem = new RowItem(uploaded_pic_name[0], pic_url.getResourceId(0, 0));
rowItems.add(uploadedItem);
//creates a new listview
mylistview = (ListView) findViewById(R.id.list);
CustomAdapter adapter = new CustomAdapter(this, rowItems);
mylistview.setAdapter(adapter);
//onclick listener on this main activity
mylistview.setOnItemClickListener(this);
btnTakePic = (ImageView) findViewById(R.id.btnTakePic);
// on click listener used to give function to the button when clicked.
btnTakePic.setOnClickListener(new View.OnClickListener() {
// onClick method defines what the function is
// Intent used to communicate to start
#Override
public void onClick(View v) {
Intent i = new Intent(Timeline.this, Camera.class);
startActivity(i);
}
});
}
//overridden method to show toast message on the picture
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String pic_name = rowItems.get(position).getPic_name();
Toast.makeText(getApplicationContext(), "" + pic_name,
Toast.LENGTH_SHORT).show();
}
}
This is the custom adapter class I had current for it
/**
* TODO
*/
public class CustomAdapter extends BaseAdapter {
//Instantiates getters for variables
Context context;
List<RowItem> rowItems;
//creates setters for variables
CustomAdapter(Context context, List<RowItem> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
//Overridden method to get the size of the rows
#Override
public int getCount() {
return rowItems.size();
}
//Overridden method to get the item position from rowItems array returning the position
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
//Overridden method to get the Item id return the position
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
/**
* private view holder class
*
*/
private class ViewHolder {
ImageView profile_pic;
TextView pic_name;
}
// Overriden method to insert image and its associated xml in the listview
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Instantiating local variables
ViewHolder holder;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//If the View is null create the layout
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
//set the textview and image view to required parameters
holder.pic_name = (TextView) convertView.findViewById(R.id.pic_name);
holder.profile_pic = (ImageView) convertView.findViewById(profile_pic);
convertView.setTag(holder);
//create a new viewholder and get the tag from the view
} else {
holder = (ViewHolder) convertView.getTag();
}
//getter for the position of the row
RowItem row_pos = rowItems.get(position);
//sets the position of the row
holder.profile_pic.setImageResource(row_pos.getProfile_pic_id());
holder.pic_name.setText(row_pos.getPic_name());
//return the view
return convertView;
}
}
These are the getters and setter for the images
public class RowItem {
private String pic_name;
private int profile_pic_id;
public RowItem(String pic_name, int profile_pic_id) {
this.pic_name = pic_name;
this.profile_pic_id = profile_pic_id;
}
//getter for the pic name
public String getPic_name() {
return pic_name;
}
//setter for the pic name
public void setPic_name(String pic_name) {
this.pic_name = pic_name;
}
//getter for the profile pic
public int getProfile_pic_id() {
return profile_pic_id;
}
//setter for the profile pic
public void setProfile_pic_id(int profile_pic_id) {
this.profile_pic_id = profile_pic_id;
}
}
Any help is much appreciated
Kindly show the code which you want to implement.
I have working code which takes an image and uploads it to my server
etc, I have the url to fetch the image from the database and i now
and on which event to implement(onClick, onItemClick etc...)
I will edit this later
Do this in, RecyclerView. There implementation is not difficult.. Your mistake is in viewholder... Read Recycler view and there will not any questions.

How to get text on selected checkbox from listview in android

I am working on android example, when i click on checkbox then it gets the textviews value of first item(Position) in listview every time. so but i want to get value of selected (position) checkbox textview value. how to solve it please help .i am a fresher.Thanks in advances.
Some Code In BaseAdapter class
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//LayoutInflater layoutInfiater = LayoutInflater.from(context);
convertView = layoutInfiater.inflate(R.layout.list_adapter_view, null);
viewItem.txtTitle = (TextView)convertView.findViewById(R.id.inactivelistview);
// viewItem.txtDescription = (TextView)convertView.findViewById(R.id.adapter_text_description);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.txtTitle.setText(valueList.get(position).username);
// viewItem.txtDescription.setText(valueList.get(position).cources_description);
return convertView;
}
Some Code in activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_in_active_list);
listCollege = (ListView)findViewById(R.id.listCollege);
proCollageList = (ProgressBar)findViewById(R.id.proCollageList);
checkbox = (CheckBox)findViewById(R.id.checkbox_me);
button =(Button)findViewById(R.id.button1);
new GetHttpResponse(this).execute();
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()) {
case R.id.checkbox_me:
if (checked) {
username = (TextView)findViewById(R.id.inactivelistview);
Username =username.getText().toString();
System.out.println("print username_=== "+Username);
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("Do you want activate "+Username+"?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), Username+" acivated", Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
} else
break;
}
I am getting textviews value of first item(Position) in listview every time.
Please help me how to solve.help me update my code
Thank you so much.......
Note that checkbox return array as user can tick multiple elements.
ArrayList<String> selectedStrings = new ArrayList<String>();
The answer describe it in details.
use gettag on onCheckboxClicked method so that you can identify which row number checkbox is click . then you can get the textview of that row use row number
If your CheckBox is in ListView then no need to create ClickListener in Activity. Follow below steps to get selected text from ListView.
First create a model/pojo class, this will help you to store reference of selected CheckBox and also values which is going to show in ListView.
public class MyModel {
private boolean isSelected;
private String name;
public MyModel(boolean isSelected, String name) {
this.isSelected = isSelected;
this.name = name;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
this.isSelected = selected;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Create a interface which will work as a callback.
public interface ItemSelectListener {
void getSelectedItemText(String text);
}
Refactor your BaseAdapter as now it will accept list of our Model class and also callback listener.
public MyAdapter extends BaseAdapter {
private final List<MyModel> mDataItems;
private final ItemSelectListener mItemListener;
public MyAdapter(List<MyModel> dataItems, ItemSelectListener itemListener)
mDataItems = dataItems;
mItemListener = itemListener;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null) {
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//LayoutInflater layoutInfiater = LayoutInflater.from(context);
convertView = layoutInfiater.inflate(R.layout.list_adapter_view, null);
viewItem.txtTitle = (TextView)convertView.findViewById(R.id.inactivelistview);
// Add checkbox in your view item and confirm id of checkbox
viewItem.checkBox = (CheckBox)convertView.findViewById(R.id. checkbox_me);
}
else {
viewItem = (ViewItem) convertView.getTag();
}
final MyModel data = mDataItems.get(position);
viewItem.txtTitle.setText(data.getName());
viewItem.checkBox.setChecked(data.isSelected());
viewItem.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton button, boolean checked)
{
data.setSelected(checked);
if(checked) {
// Make sure you override this in your Activity
mItemListener.getSelectedItemText(data.getName());
}
}
});
return convertView;
}
}
Create datasource for ListView in your Activity.
BaseAdapter adapter = new BaseAdapter(dataItems, itemListener);

Delete Button in Listview from SQLiteDatabase

I was wondering if somebody could further explain how to implement a delete button inside a listview that is populated from an SQLite database. I've read the responses to the following question that is essentially what I'm asking as well, but I don't understand it:
How can I implement a delete button in a ListView and delete from database?
In my custom row .xml file, I included a delete button that implements the method delete() onClick. It also includes an alert dialog, by the way. Here's the code that I have so far for my delete() method; whenever I try to use it, it never gets the right activtiy entry.
public void delete(View view){
final int position = listview.getPositionForView((View) view.getParent());
String id = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_ID));
AlertDialog.Builder myDialog = new AlertDialog.Builder(MainActivity.this);
myDialog.setTitle("Delete activity entry \"" + id + "\"?");
myDialog.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
mySQLiteAdapter.delete(position);
cursor.requery();
}
});
myDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialog.show();
}
A solution is to implement a custom ArrayAdapter.
public class MyArrayAdapter extends ArrayAdapter<YourObject>
{
private ArrayList<YourObject> items;
public LiftArrayAdapter(Context context, int textViewResourceId, ArrayList<YourObject> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.your_view_xml, null);
}
final YourObject obj = items.get(position);
TextView lblLift = (TextView) v.findViewById(R.id.lbl_lift);
ImageButton btnDelete = (ImageButton) v.findViewById(R.id.btn_delete);
btnDelete .setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//TODO delete 'obj' from database
}
});
return v;
}
}
Then, to bind a list of objects to your listview:
List<YourObject> list = ...
MyArrayAdapter myArrayAdapter = new MyArrayAdapter (.., .. , list);
listView.setAdapter(myArrayAdapter);

Android Java: Unable to selectively highlight rows in a ListView via onScroll listener

I have another blocker as I study Android Development.
This time my problem is when I wanted to "selectively" highlight a row in a ListView populated by data from an adapter.
This ListView is actually within a dialog, and purpose is to show a list of friends, where user can multi-select and highlight it as he selects.
The selected values by the way, is stored in an ArrayList "arr_FriendsShare" so that the next time he opens the listview, rows will be highlighted (via onScrollListener) for those previously selected.
What is currently happening, only the "recently" or "last" clicked row/item is highlighted; and seems to be clearing all the previously highlighted rows.
I cannot understand why it is behaving that way, as row's value is successfully stored to/removed from arr_FriendsShare ArrayList, as I click on it.
Below is my listener codes, and thanks in advance for the usual help:
//Item click listener for Select Friends ListView
listview_SelectFriends.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String friends_ListItemSelected = (String)adapter.getItemAtPosition(position);
if(!arr_FriendsShare.contains(friends_ListItemSelected)){
arr_FriendsShare.add(friends_ListItemSelected);
}
else{
removeItemFromArrayListString(Main.this, arr_FriendsShare, friends_ListItemSelected);
}
}
});
listview_SelectFriends.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
for (int i = firstVisibleItem; i < (visibleItemCount + firstVisibleItem); i++) {
String listViewItemText = view.getItemAtPosition(i).toString();
if(arr_FriendsShare.contains(listViewItemText)){
ColorDrawable cd = new ColorDrawable(getResources().getColor(R.color.red_light));
view.setSelector(cd);
}
else if(arr_FriendsShare.contains(listViewItemText)){
ColorDrawable cd = new ColorDrawable(Color.TRANSPARENT);
view.setSelector(cd);
}
}
}
});
Additional Code Block:
ArrayList<String> stringArray = new ArrayList<String>();
String jsonURL = <SOME URL HERE>;
stringArray = Global.getStringArrayFromJSON(Main.this, jsonURL, "friends", "FriendUsername");
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.friends_list_layout, null);
ListView listview_SelectFriends = (ListView) convertView.findViewById(R.id.layout_Friends);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringArray);
listview_SelectFriends.setAdapter(adapter);
Change
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringArray);
to
// Define this at class level as --> private FriendsAdapter adapter = null;
adapter = new FriendsAdapter(Main.this, stringArray);
add this method in your activity
private void setResetSelection(int index, boolean setSelection){
View v = listview_SelectFriends.getChildAt(index);
if(v != null){
TextView name = (TextView) v.findViewById(R.id.name);
if(setSelection)
name.setBackgroundResource(R.color.red);
else
name.setBackgroundResource(R.color.transparent);
}
}
and create a new class as
public class FriendsAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<String> mFriends;
private ArrayList<String> mSelectedFriends = new ArrayList<String>();
public GoodPeopleAdapter(Context context, ArrayList<String> friends) {
mInflater = LayoutInflater.from(context);
mFriends= friends;
}
public void setSelectedFriends(ArrayList<String> selectedFriends){
mSelectedFriends = selectedFriends;
}
#Override
public int getCount() {
return mFriends.size();
}
#Override
public Object getItem(int position) {
return mFriends.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder holder;
if(convertView == null) {
view = mInflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.name = (TextView)view.findViewById(R.id.name);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
String name = mFriends.get(position);
holder.name.setText(name);
if(mSelectedFriends.contains(name))
holder.name.setBackgroundResource(R.color.red) // red is in color xml by default, change according to your choice
return view;
}
private class ViewHolder {
public TextView name;
}
}
Add following line at the end of method onItemClick
adapter.setSelectedFriends(arr_FriendsShare);
Add this in the if part of onItemClick
setResetSelection(position, true);
and this in else part
setResetSelection(position, false);
Also create a new xml layout with name row_layout with a textview with id name.

Android listview showing only last element

i created custom listview with text and two buttons, i set up arraylist and adapter but my listview is showing every element as last, for ex. if i add 3 elements: "text1","text2","text3" my listview shows "text3", "text3" "text3" and i dont have any idea why.
private ListView lista;
private List<Piosenka> listaPiosenek;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);
lista = (ListView) findViewById(R.id.listView1);
lista.setClickable(true);
}
public void update_listy() throws MalformedURLException, IOException
{
final List<Piosenka> listaPiosenek = new ArrayList<Piosenka>();
listaPiosenek.add(new Piosenka("text1"));
listaPiosenek.add(new Piosenka("text2"));
listaPiosenek.add(new Piosenka("text3"));
PiosenkaAdapter adapter = new PiosenkaAdapter(this, listaPiosenek);
lista.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long index)
{
System.out.println("sadsfsf");
}
});
lista.setAdapter(adapter);
}
Edit: PiosenkaAdapter code
public class PiosenkaAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private List<Piosenka> listapiosenek;
public PiosenkaAdapter(Context context, List<Piosenka> listapiosenek) {
this.context = context;
this.listapiosenek = listapiosenek;
}
public int getCount() {
return listapiosenek.size();
}
public Object getItem(int position) {
return listapiosenek.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
Piosenka element = listapiosenek.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_element, null);
}
TextView tvTytul = (TextView) convertView.findViewById(R.id.tvTytul);
tvTytul.setText(Piosenka.getTytul());
Button btnPobierz = (Button) convertView.findViewById(R.id.btnPobierz);
btnPobierz.setFocusableInTouchMode(false);
btnPobierz.setFocusable(false);
btnPobierz.setTag(element);
Button btnPlay = (Button) convertView.findViewById(R.id.btnPlay);
btnPlay.setFocusableInTouchMode(false);
btnPlay.setFocusable(false);
btnPlay.setOnClickListener(this);
btnPlay.setTag(element);
// btnRemove.setId(position);
return convertView;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPobierz:
Piosenka entry = (Piosenka) view.getTag();
listapiosenek.remove(entry);
notifyDataSetChanged();
break;
case R.id.btnPlay:
entry = (Piosenka) view.getTag();
listapiosenek.remove(entry);
notifyDataSetChanged();
break;
}
}
}
Try this...
lista.setAdapter(adapter);
adapter.notifyDataSetChanged();
Can you paste you PiosenkaAdapter's code?
I don't know your language, but the Piosenka variable is fetched correctly in getView()
Piosenka element = listapiosenek.get(position);
But this looks strange to me
TextView tvTytul = (TextView) convertView.findViewById(R.id.tvTytul);
tvTytul.setText(Piosenka.getTytul());
Piosenka.getTytul() looks to me as a static method call, where you should do a regular method call to element.getTytul() instead.

Categories

Resources