How to get values from dynamically created LinearLayout in android - android

I'm new to android. Started learning recently.
I have created a LinearLayout dynamically. I have the following fields in LinearLayout:
1. Customer name
2. Edit Button
3. Delete Button.
Orientation is horizontal.
Now I want to delete a single record when I click on delete button. How can I get row id in this case and later I can pass to database to delete the record. Here is the code.
user_list_view_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg_main"
>
<TextView android:id="#+id/txtTitle"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:textStyle="bold"
android:textSize="50dp"
android:textColor="#FFFFFF"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<Button
android:id="#+id/userListEditButton"
style="#style/SpecialText"
android:layout_width="50dp"
android:layout_height="50dp"
android:typeface="monospace"
android:text="#string/save"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<Button
android:id="#+id/userListDeleteButton"
style="#style/SpecialText"
android:layout_width="50dp"
android:layout_height="50dp"
android:typeface="monospace"
android:text="#string/reset"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</LinearLayout>
UserAdapter.java
package com.rad.mobileshop.activities;
import java.sql.SQLException;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.rad.mobileshop.common.entities.User;
import com.rad.mobileshop.db.DBAdapter;
public class UserAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
User data[] = null;
private DBAdapter mdb;
public UserAdapter(Context context, int layoutResourceId, User[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
mdb = new DBAdapter(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.txtTitle);
holder.editButton = (Button) row
.findViewById(R.id.userListEditButton);
holder.deleteButton = (Button) row
.findViewById(R.id.userListDeleteButton);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data[position];
holder.txtTitle.setText(user.getName());
holder.editButton.setText("Edit");
holder.deleteButton.setText("Delete");
holder.editButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
System.out.println("hello Edit");
}
});
holder.deleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
System.out.println("hello delete ");
}
});
return row;
}
private void deleteUserDetails(int userId) {
try {
mdb.open();
mdb.deleteUserDetails(userId);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
static class UserHolder {
TextView txtTitle;
Button editButton;
Button deleteButton;
}
}
User.java
package com.rad.mobileshop.common.entities;
public class User {
private int id;
private String name;
private String type;
public User() {
super();
}
public User(int id, String name, String type) {
super();
this.id = id;
this.name = name;
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return this.name ;
}
}

First you need to change your User[] array into an ArrayList, because you cannot dynamically remove an element for a primitive array. (At least not as easily and ArrayAdapter is already designed to work with ArrayLists in this circumstance.)
Next let's save position in deleteButton in getView() for easy access:
holder.deleteButton.setTag(position);
Last add this to your delete OnClickListener:
public void onClick(View view) {
User user = getItem((Integer) view.getTag()));
remove(user);
deleteUserDetails(user.getId());
}
There are an couple minor adjustments that I didn't cover, like changing UserAdapter's constructor and data[position] in getView(), but they are easy fixes.
Optional advice:
You should create only one LayoutInflater in your constructor and simply re-use it in getView()
You don't need to store a copy of data in UserAdapter, it is already stored in ArrayAdapter, simply access it with getItem(position).
You can streamline getView() by moving every command that doesn't change into the if(row == null) block.
All that said, I'm not sure why you extended ArrayAdapter if you are working with a database. I suggest switching to a custom CursorAdapter, but this isn't required.

Related

How to fix Android ListView Rendering Error where the checkboxes of the list items disappear?

I am developing an android app where I use a listview which has a checkbox in each row item. But when it scrolls up or down, random rows remove the checkboxes which ends in no checkboxes showing in the entire list. I have tried many solutions given in online tutorials, but none of them work. All of them show it using a ViewHolder class. Could you please help me?
Here is all the code I can provide:
List Item XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<ImageView
android:id="#+id/user_image_view"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_margin="16dp"
tools:src="#mipmap/ic_account_circle_bue" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingRight="16dp"
android:layout_centerVertical="true">
<TextView
android:id="#+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="19dp"
android:textStyle="bold"
android:ellipsize="end"
android:maxLines="1"
android:textColor="#000000"
android:paddingRight="5dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/user_roll_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Roll Number"
android:textSize="15dp" />
<TextView
android:id="#+id/user_department"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="12dp"
android:text="Department"
android:textSize="15dp"
android:maxLines="1"
android:ellipsize="end"/>
</LinearLayout>
</LinearLayout>
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
UsersSelection (Model Class):
package com.app.shubhamjhunjhunwala.heritagecompanion_students;
/**
* Created by shubham on 09/05/17.
*/
public class UsersSelection {
public Users users;
public boolean isSelected;
public UsersSelection (Users users, boolean isSelected) {
this.users = users;
this.isSelected = isSelected;
}
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
Users.java (Custom class):
package com.app.shubhamjhunjhunwala.heritagecompanion_students;
/**
* Created by shubham on 23/01/17.
*/
public class Users {
String name;
String department;
String roll;
String dpDownloadUri;
Users() {}
public Users(String name, String department, String roll, String dpDownloadUri) {
this.name = name;
this.department = department;
this.roll = roll;
this.dpDownloadUri = dpDownloadUri;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getDpDownloadUri() {
return dpDownloadUri;
}
public void setDpDownloadUri(String dpDownloadUri) {
this.dpDownloadUri = dpDownloadUri;
}
}
Custom Array Adapter for List View:
package com.app.shubhamjhunjhunwala.heritagecompanion_students;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
* Created by shubham on 09/05/17.
*/
public class UsersSelectionAdapter extends ArrayAdapter<UsersSelection> {
public Context context;
public String roll;
public boolean isForGroup;
public List<GroupMembers> groupMembersList;
public List<UsersSelection> list;
public CheckBox checkBox;
public UsersSelectionAdapter(Context context, int resource, List<UsersSelection> objects) {
super(context, resource, objects);
this.context = context;
list = objects;
}
public class ViewHolder {
TextView nameTextView;
TextView rollNumberTextView;
TextView departmentTextView;
ImageView dpImageView;
CheckBox checkBox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
SharedPreferences sharedPreferences = ((Activity) getContext()).getSharedPreferences("HCS", 0);
roll = sharedPreferences.getString(AuthenticationActivity.ROLL_SHARED_PREFERENCE_KEY, "");
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.user_list_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.nameTextView = (TextView) convertView.findViewById(R.id.user_name);
viewHolder.departmentTextView = (TextView) convertView.findViewById(R.id.user_department);
viewHolder.rollNumberTextView = (TextView) convertView.findViewById(R.id.user_roll_number);
viewHolder.dpImageView = (ImageView) convertView.findViewById(R.id.user_image_view);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (int) buttonView.getTag();
list.get(getPosition).setSelected(buttonView.isSelected());
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.user_name, viewHolder.nameTextView);
convertView.setTag(R.id.user_department, viewHolder.departmentTextView);
convertView.setTag(R.id.user_roll_number, viewHolder.rollNumberTextView);
convertView.setTag(R.id.user_image_view, viewHolder.dpImageView);
convertView.setTag(R.id.checkbox, viewHolder.checkBox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkBox.setTag(position);
/*TextView nameTextView = (TextView) convertView.findViewById(R.id.user_name);
TextView departmentTextView = (TextView) convertView.findViewById(R.id.user_department);
TextView rollNumberTextView = (TextView) convertView.findViewById(R.id.user_roll_number);
ImageView dpImageView = (ImageView) convertView.findViewById(R.id.user_image_view);
checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);*/
UsersSelection usersSelection = getItem(position);
Users user = usersSelection.getUsers();
if (!isForGroup) {
viewHolder.checkBox.setVisibility(View.GONE);
} else {
if (user.getRoll().equals(roll)) {
viewHolder.checkBox.setVisibility(View.GONE);
}
}
viewHolder.nameTextView.setText(user.getName());
viewHolder.nameTextView.setTag(usersSelection);
viewHolder.departmentTextView.setText(user.getDepartment());
viewHolder.departmentTextView.setTag(usersSelection);
viewHolder.rollNumberTextView.setText(user.getRoll());
viewHolder.rollNumberTextView.setTag(usersSelection);
viewHolder.checkBox.setChecked(list.get(position).isSelected());
viewHolder.checkBox.setTag(usersSelection);
Bitmap bitmap = null;
if (!user.getDpDownloadUri().equals("")) {
DPAsyncTask dpAsyncTask = new DPAsyncTask(context, viewHolder.dpImageView.getContext(), viewHolder.dpImageView, user);
dpAsyncTask.execute();
} else {
Glide.clear(viewHolder.dpImageView);
viewHolder.dpImageView.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.ic_account_circle_bue));
}
return convertView;
}
public boolean isForGroup() {
return isForGroup;
}
public void setForGroup(boolean forGroup) {
isForGroup = forGroup;
}
public List<GroupMembers> getGroupMembersList() {
return groupMembersList;
}
public void setGroupMembersList(List<GroupMembers> groupMembersList) {
this.groupMembersList = groupMembersList;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
}
Thank You for going through my issue. Hope you help :)
if (!isForGroup) {
viewHolder.checkBox.setVisibility(View.GONE);
} else {
if (user.getRoll().equals(roll)) {
viewHolder.checkBox.setVisibility(View.GONE);
}
}
You only ever make the CheckBox GONE. You never reset it to be VISIBLE.
Remember that the point behind ListView, other AdapterView classes, and RecyclerView is to recycle views. You cannot, and should not, assume that your widgets are in any particular state in getView(). If you modify a widget (e.g., change its visibility), you need to modify that state all the time.
So, change the above code to:
if (!isForGroup || user.getRoll().equals(roll)) {
viewHolder.checkBox.setVisibility(View.GONE);
} else {
viewHolder.checkBox.setVisibility(View.VISIBLE);
}
or something like that, so that you always state whether the CheckBox should be visible or not.

ListView by an ArrayList of serializable objects

Now I have a serializable Object Class called Tasks, I intend to make a Listview, each object represent an item within the list but when I run the code it does not work
this is the Main Activity :
public class MainActivity extends ActionBarActivity {
EditText NameET, ImportanceED, dateED, TimeED;
String Name, Importance, date, Time;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NameET = (EditText) findViewById(R.id.NameeditText);
ImportanceED = (EditText) findViewById(R.id.ImportanceeditText2);
dateED = (EditText) findViewById(R.id.dateeditText3);
TimeED = (EditText) findViewById(R.id.timeeditText4);
public void GetTexts() {
Name = NameET.getText().toString();
Importance = ImportanceED.getText().toString();
date = dateED.getText().toString();
Time = TimeED.getText().toString();
}
public void AddTask(View view) {
String testName = NameET.getText().toString().trim();
String testImportance = ImportanceED.getText().toString().trim();
String testDate = dateED.getText().toString().trim();
String testTime = TimeED.getText().toString().trim();
GetTexts();
OpenDetailsActivity();
}
}
public void OpenDetailsActivity() {
Intent DetailsIntent = new Intent(this, DetailsActivity.class);
DetailsIntent.putExtra("Name",Name );
DetailsIntent.putExtra("Importance",Importance );
DetailsIntent.putExtra("date",date );
DetailsIntent.putExtra("Time",Time );
startActivity(DetailsIntent);
}
and this is the List containing activity :
public class DetailsActivity extends Activity {
ListView list;
String Name;
String Importance;
String date;
String Time ;
ArrayList <Tasks>TaskList = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task_list);
Intent intent = getIntent();
Name= intent.getStringExtra("Name");
Importance= intent.getStringExtra("Importance");
date= intent.getStringExtra("date");
Time= intent.getStringExtra("Time");
addToList();
}
public void addToList() {
int i ;
int N = TaskList.size();
if (N > 0 ){
i = N + 1 ;
} else {
i= 0 ;
}
Everything works fine untill here , the list appears blank
TaskList.add(i, new Tasks(Name, Importance, date, Time));
ListAdapter adapter = new ListAdapter(this, TaskList);
list = (ListView) findViewById(R.id.listView_tasks);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String SelectedTask = TaskList.get(position).getName();
Toast.makeText(getApplicationContext(), SelectedTask, Toast.LENGTH_SHORT).show();
this is Tasks Serializable class
class Tasks implements Serializable {
String name="";
String date="";
String time = "";
String importance="";
public Tasks(String name, String importance, String date , String time) {
this.date = date;
this.importance = importance;
this.name = name;
this.time = time;
}
public String getDate() {
return date;
}
public String getImportance() {
return importance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTime() {
return time;
}
and this is the custom adapter
public class ListAdapter extends ArrayAdapter {
private final Activity context;
List<Tasks> TaskList;
public ListAdapter(Activity context, List<Tasks> TaskList) {
super(context, R.layout.row_layout);
this.context=context;
this.TaskList=TaskList;
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.row_layout, null , false);
TextView Name = (TextView) rowView.findViewById(R.id.NameTV);
TextView Date = (TextView) rowView.findViewById(R.id.dateTV);
TextView Importance = (TextView) rowView.findViewById(R.id.importanceTV);
TextView Time = (TextView) rowView.findViewById(R.id.timeTV);
TaskList.get(position).getName();
Name.setText(TaskList.get(position).getName());
Date.setText(TaskList.get(position).getDate());
Importance.setText(TaskList.get(position).getImportance());
Time.setText(TaskList.get(position).getTime());
return rowView;
this is task_list Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView_tasks" />
</LinearLayout>
and this row_layout
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/NameTV"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/importanceTV" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/dateTV" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/timeTV" />
</LinearLayout>
</LinearLayout>
I have do some changes in your code, I tested it on my pc and it is working.
I only update ListAdapter.java and It works.
ListAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Usman Asghar on 23/02/2016.
*/
public class ListAdapter extends ArrayAdapter {
Context context;
List<Tasks> TaskList;
public ListAdapter(Activity context, List<Tasks> TaskList) {
super(context, R.layout.row_layout,TaskList);
this.context = context;
this.TaskList = TaskList;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_layout, null, false);
}
TextView Name = (TextView) view.findViewById(R.id.NameTV);
TextView Date = (TextView) view.findViewById(R.id.dateTV);
TextView Importance = (TextView) view.findViewById(R.id.importanceTV);
TextView Time = (TextView) view.findViewById(R.id.timeTV);
Name.setText(TaskList.get(position).getName());
Date.setText(TaskList.get(position).getDate());
Importance.setText(TaskList.get(position).getImportance());
Time.setText(TaskList.get(position).getTime());
return view;
}
}
I changed ArrayAdapter constructor to
super(context, R.layout.row_layout);
That
super(context, R.layout.row_layout,TaskList);
ArrayAdapter does not work until we do not specify what data we want to show on ListView.
And I Do some little Changes in getView() method.
Add to your adapter this method:
#Override
public int getCount() {
return TaskList.size();
}
Change this:
TaskList.add(i, new Tasks(Name, Importance, date, Time));
to this:
TaskList.add(new Tasks(Name, Importance, date, Time));

Android: CustomListView with CustomAdapter, Call Button is not working

In my app I have 3 views
ImagiveView
TextView
Button
ImagView displays image accordingly, TextView and Button display names and number accordingly. But the problem is when I click on the button it does not call to the number which is displaying on the button. Although it does open the android caller app.
Telephone numbers are in string.xml file.
Here I provide my all files. Please help me
strings.xml
<string-array name="names">
<item>Abdul Malik</item>
<item>Adeel ur Rehman</item>
<item>Asad Majeeb</item>
<item>Ata ul Salam</item>
<item>Atta ul Qadir</item>
<item>Bilal Scunder</item>
<item>Chaudry Adnan Ahmed</item>
<item>Chaudry Imran</item>
<item>Ejaz Ahmed Saroya</item>
<item>Hamid Joya</item>
</string-array>
<string-array name="telephones">
<item>0000000000</item>
<item>0486607636</item>
<item>0485256515</item>
<item>0485128196</item>
<item>0465922084</item>
<item>0487150005</item>
<item>0488627993</item>
<item>0484783792</item>
<item>0484688663</item>
<item>0497697050</item>
</string-array>
MainActivity.xml
package com.example.android.listview_with_custom_layout;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
ListView listView;
int [] movie_poster_resource={
R.drawable.movie_1,
R.drawable.movie_2,
R.drawable.movie_3,
R.drawable.movie_4,
R.drawable.movie_5,
R.drawable.movie_6,
R.drawable.movie_7,
R.drawable.movie_8,
R.drawable.movie_9,
R.drawable.movie_10,
};
String [] names ={};
String [] telephones ={};
MoviesAdapter moviesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView) findViewById(R.id.list_view);
telephones =getResources().getStringArray(R.array.telephones);
names =getResources().getStringArray(R.array.names);
int i=0;
moviesAdapter= new MoviesAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(moviesAdapter);
for(String titles: names){
MovieDataProvider movieDataProvider= new MovieDataProvider(movie_poster_resource[i], titles, telephones[i]);
moviesAdapter.add(movieDataProvider);
i++;
}
}
}
MoviesDataAdapter
package com.example.android.listview_with_custom_layout;
/**
* Created by temp on 2/11/2015.
*/
public class MovieDataProvider {
private int movie_poster_resource;
private String movie_title;
private String telePhone;
public MovieDataProvider(int movie_poster_resource, String movie_title, String telePhone) {
this.setMovie_poster_resource(movie_poster_resource);
this.setMovie_title(movie_title);
this.telePhone = telePhone;
}
public int getMovie_poster_resource() {
return movie_poster_resource;
}
public String getMovie_title() {
return movie_title;
}
public String getTelePhone() {
return telePhone;
}
public void setMovie_poster_resource(int movie_poster_resource) {
this.movie_poster_resource = movie_poster_resource;
}
public void setMovie_title(String movie_title) {
this.movie_title = movie_title;
}
public void setTelePhone(String telePhone) {
this.telePhone = telePhone;
}
}
MoviesAdapter
package com.example.android.listview_with_custom_layout;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by temp on 2/11/2015.
*/
public class MoviesAdapter extends ArrayAdapter {
List list = new ArrayList();
MovieDataProvider dataProvider;
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();
}
dataProvider = (MovieDataProvider) this.getItem(position);
handler.Poster.setImageResource(dataProvider.getMovie_poster_resource());
handler.title.setText(dataProvider.getMovie_title());
handler.telePhone.setText(dataProvider.getTelePhone());
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()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
});
return row;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffd953"
tools:context=".MainActivity">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#000000"
android:orientation="vertical"
android:paddingTop="10dp">
<ImageView
android:id="#+id/movie_poster"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:src="#drawable/movie_1" />
<TextView
android:id="#+id/movie_title"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_toRightOf="#+id/movie_poster"
android:gravity="center"
android:text="This is movie name"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/btn_call"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/movie_title"
android:gravity="center"
android:text="call"
android:textColor="#FFFF" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_below="#+id/movie_poster"
android:background="#FFFF"></View>
</RelativeLayout>
you forgot to initialize the telephones string in your MainActivity, do same as you did for movie_poster_resource after this it should work, and dont forgot to add permission
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
and last you can update the button click code with
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+dataProvider.getTelePhone()));
startActivity(callIntent);
and update your AdapterClass with this
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;
final MovieDataProvider dataProvider = (MovieDataProvider) this.getItem(position);;
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);
} else {
handler = (DataHandler) row.getTag();
}
handler.Poster.setImageResource(dataProvider.getMovie_poster_resource());
handler.title.setText(dataProvider.getMovie_title());
handler.telePhone.setText(dataProvider.getTelePhone());
handler.telePhone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + dataProvider.getTelePhone()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(intent);
}
});
row.setTag(handler);
return row;
}
}

how to insert an image into a listview?

I would like to insert a small image to the right of each item in a listview
basically my app should do so as soon as the user clicks on an item in the list view, the image becomes visible, otherwise it must remain invisible.
below is my activity with its XML
Activity
public class EpisodiActivity extends Activity {
public class ViewModel {
private String url;
private String name;
public ViewModel(String url, String name) {
this.url = url;
this.name = name;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//creazione fullscreen activity
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.episodi_activity);
String[] episodi = getIntent().getStringArrayExtra("Product");
String[] urls = getIntent().getStringArrayExtra("urls");
ListView mylist = (ListView) findViewById(R.id.listView1);
// And in this loop we create the ViewModel instances from
// the name and url and add them all to a List
List<ViewModel> models = new ArrayList<ViewModel>();
for (int i = 0; i < episodi.length; i++) {
String name = episodi[i];
String url = "No value";
if (i < urls.length) {
url = urls[i];
}
ViewModel model = new ViewModel(url, name);
models.add(model);
}
// Here we create the ArrayAdapter and assign it to the ListView
// We pass the List of ViewModel instances into the ArrayAdapter
final ArrayAdapter<ViewModel> adapter = new ArrayAdapter<ViewModel>(this, android.R.layout.simple_list_item_1, models);
mylist.setAdapter(adapter);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Here we get the ViewModel at the given position
ViewModel model = (ViewModel) arg0.getItemAtPosition(position);
// And the url from the ViewModel
String url = model.getUrl();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
});
}
XML
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/pubblicita"
android:cacheColorHint="#ffd700"
android:background="#drawable/sfondobottone" />
I think you want this kind of output in listview
text with image in listview
You can use custom listview . Make a class which extends BaseAdapter class
here is the exmaple that i am using
Your BaseAdapter
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class FrontListBaseAdapter extends BaseAdapter {
private static ArrayList<FrontDetails> itemDetailsrrayList;
private LayoutInflater l_Inflater;
public FrontListBaseAdapter(Context context, ArrayList<FrontDetails> results) {
itemDetailsrrayList = results;
l_Inflater = LayoutInflater.from(context);
}
public int getCount() {
return itemDetailsrrayList.size();
}
public Object getItem(int position) {
return itemDetailsrrayList.get(position);
}
public long getItemId(int position) {
return position;
}
// get the views in frontview xml file where you have
// define multiple views that will appear in listview each row
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = l_Inflater.inflate(R.layout.frontview, null);
holder = new ViewHolder();
holder.Image = (ImageView) convertView.findViewById(R.id.adminpic1);
holder.MsgType = (TextView) convertView.findViewById(R.id.msgtype1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.Image.setImageResource(R.drawable.mainlogo); // you can set your setter here
holder.MsgType.setText(itemDetailsrrayList.get(position).getMsgType());
return convertView;
}
// holder view for views
static class ViewHolder {
ImageView Image;
TextView MsgType;
}
}
your FrontDetails class where you will make getters and setters and this class will be used in final ArrayList resultse = new ArrayList();
import android.graphics.Bitmap;
public class FrontDetails {
public int getImage() {
return image;
}
public void setImage(int imageN) {
this.image = imageN;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String text) {
this.MsgType = text;
}
private int image;
private String MsgType;
}
your frontview.XML where you put your multiple views that will be in each row or your layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:layout_margin="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp" >
<ImageView
android:id="#+id/adminpic1"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/msgtype1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:textSize="1sp"
android:text="MsgType" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
and your listview in xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/sync"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sync" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp" >
</ListView>
</LinearLayout>
now in your main activity
final ArrayList<FrontDetails> resultse = new ArrayList<FrontDetails>();
FrontListBaseAdapter asdf = new FrontListBaseAdapter(context, resultse);
lv1.setAdapter(new FrontListBaseAdapter(Front.this, resultse));
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Object o = lv1.getItemAtPosition(position);
FrontDetails obj_itemDetails = (FrontDetails)o;
Toast.makeText(context, "You have chosen " + ' ' + obj_itemDetails.getMsgType(), Toast.LENGTH_LONG).show();
}
});
EDIT:
From here i learned Custom Listview its a simple exmaple with image
http://www.javasrilankansupport.com/2012/05/android-listview-example-with-image-and.html
http://www.javacodegeeks.com/2012/10/android-listview-example-with-image-and.html
Use custom listview with BaseAdapter
Your Adapter
public class CustomBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
Your list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/icon"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/image"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icon"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_toRightOf="#+id/icon"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
</RelativeLayout>
Your Single Row item class
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
List view implementation
listView = (ListView) findViewById(R.id.list);
CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
I can give some tips ,but unfortunately couldn't help you by example..
First of all create one custom adapter(extends BaseAdapter) followed by one custom layout..
Here the custom layout contains the textview and one image view(by default invisible) at the right.
Just customize your list view with your adapter and put text inside TextView through get view()..
At last in your listItemClickListener make the image visible by its position.
You can set here on xml like this
android:visibility="visible"
or
android:visibility="invisible"
or
android:visibility="gone"
Java program:
ImageView imgView = (ImageView)findViewById(R.id.custom);
set your ImageView like this
imgView .setVisibility(View.VISIBLE);
imgView .setVisibility(View.INVISIBLE);
imgView .setVisibility(View.GONE);
Difference between INVISIBLE and GONE.
INVISIBLE - The widget will be invisible but space for the widget will be show.
GONE - Both space and widget is invisible.
Now you can hook your setOnItemClickListener()
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
imgView .setVisibility(View.VISIBLE);
}
});

Android ListView ViewHolder only displaying one view

I'm having a weird problem with my viewholders. I'm trying to create an activity that allows the user to choose multiple dates from datepicker dialog (this works) and then make a list of the chosen dates and add a timepicker for each of them. E.g 22-02-2014 14:00 (the 14:00 depicting a timepicker for that date). So if 5 dates were chosen, 5 rows would appear with each containing a chosen date and its own timepicker.
Currently creating the list from chosen dates works but timepicker won't appear no matter what I attempt. Only the textview containing the date is shown in the holder.
I've been searching for solution for several hours but I can't seem to find similar issues which indicates something is seriously wrong on my end. Just can't fathom what that might be.
The relevant code (omitting the activity itself since it works as supposed with list and all):
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
public class RandomListAdapter extends ArrayAdapter<String> {
static Context mContext;
private static class ViewHolder {
private View row;
private TextView date;
private TimePicker tp;
public ViewHolder(View row) {
this.row = row;
}
public void setDate(String date) {
this.date.setText(date);
}
public void initTp(TimePicker tp){
this.tp = tp;
}
public void setHour(int h) {
tp.setCurrentHour(h);
}
public void setMin(int m){
tp.setCurrentMinute(m);
}
public TextView getDate() {
if(date==null) {
date = (TextView) row.findViewById(R.id.rr_date_item);
}
return date;
}
public TimePicker getTp() {
if(tp==null) {
tp = (TimePicker) row.findViewById(R.id.rr_tp);
}
return tp;
}
}
private static RandomListAdapter instance = null;
private ArrayList<String> items;
public RandomListAdapter(Context context) {
super(context, 0);
mContext = context;
items = new ArrayList<String>();
}
public void updateList(ArrayList<String> l){
items = l;
super.notifyDataSetChanged();
}
#Override
public int getCount() {
return items.size();
}
#Override
public String getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String s = (String)items.get(position);
ViewHolder vH = null;
if(convertView == null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(R.layout.rr_row_layout, null);
vH = new ViewHolder(convertView);
vH.date = vH.getDate();
vH.tp = vH.getTp();
convertView.setTag(vH);
}
else {
vH = (ViewHolder) convertView.getTag();
}
if(vH != null && s != null) {
vH.setDate(s);
}
return convertView;
}
public static RandomListAdapter getInstance(Context mContext) {
if(instance == null) {
instance = new RandomListAdapter(mContext);
}
return instance;
}
}
The xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:minHeight="?android:attr/listPreferredItemHeight"
android:orientation="horizontal"
android:showDividers="middle"
android:divider="?android:attr/dividerHorizontal" >
<TextView
android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
android:id="#+id/rr_date_item"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical|left"
android:ellipsize="end"
android:singleLine="true"
android:layout_weight="0"
android:textAlignment="gravity"
android:textSize="18sp" />
<TimePicker
android:id="#+id/rr_tp"
android:layout_width="0dip"
android:layout_height="0dip"
android:layout_weight="1" />
</LinearLayout>
Thanks in advance and my apologies if I'm missing something obvious.
This could be a problem
android:layout_height="0dip"
on your TimePicker. Change the height to wrap_content. Only the width needs to be 0dp when using weight.

Categories

Resources