I want to add edittext on list item on button click of that particular list item. I need to get texts in the edittexts. I have posted the code I managed to come up with. But when I scroll the listview the edittexts get added to other list items as well. Pls help...
MainActivity:
ArrayList<EdittextValues> etValues = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<ListItemModel> arrayList = new ArrayList<>();
arrayList.add(new ListItemModel("Title 1"));
arrayList.add(new ListItemModel("Title 2"));
arrayList.add(new ListItemModel("Title 3"));
arrayList.add(new ListItemModel("Title 4"));
arrayList.add(new ListItemModel("Title 5"));
arrayList.add(new ListItemModel("Title 6"));
arrayList.add(new ListItemModel("Title 7"));
arrayList.add(new ListItemModel("Title 8"));
arrayList.add(new ListItemModel("Title 9"));
arrayList.add(new ListItemModel("Title 10"));
ListView lv = (ListView)findViewById(R.id.listview);
lv.setItemsCanFocus(true);
final CustomListAdapter adapter = new CustomListAdapter(MainActivity.this, arrayList, etValues);
lv.setAdapter(adapter);
Button btn = (Button)findViewById(R.id.show);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String all="";
for (int i=0; i<etValues.size(); i++){
all += etValues.get(i).getValue()+"\n";
}
Toast.makeText(MainActivity.this, all, Toast.LENGTH_LONG).show();
}
});
}
CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
ArrayList<ListItemModel> items;
ViewHolder holder;
Context mContext;
ArrayList<EdittextValues> etValues;
int i = 0;
public CustomListAdapter(Context context, ArrayList<ListItemModel> items, ArrayList<EdittextValues> etValues) {
this.mContext = context;
this.items = items;
this.etValues = etValues;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_row, null);
holder.tvTitle = (TextView) convertView.findViewById(R.id.title);
holder.btnAdd = (Button) convertView.findViewById(R.id.addEdittext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvTitle.setText(items.get(position).getTitle());
final View finalConvertView = convertView;
holder.btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
etValues.add(new EdittextValues(position, i, ""));
LinearLayout mLayout = (LinearLayout) finalConvertView.findViewById(R.id.llChild);
LinearLayout.LayoutParams mparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
final EditText myEditText = new EditText(mContext);
mparams.setMargins(46, 3, 46, 3);
myEditText.setLayoutParams(mparams);
mLayout.setOrientation(LinearLayout.VERTICAL);
myEditText.setPadding(10, 10, 10, 10);
myEditText.setSingleLine(true);
myEditText.setId(i);
myEditText.setHeight(72);
myEditText.setTextSize(15);
myEditText.setFocusableInTouchMode(true);
myEditText.setFocusable(true);
myEditText.setHint("Type");
mLayout.addView(myEditText);
myEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
etValues.get(myEditText.getId()).setValue(charSequence+"");
Toast.makeText(mContext, etValues.get(myEditText.getId()).getValue(), Toast.LENGTH_SHORT).show();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
i++;
}
});
return convertView;
}
private class ViewHolder {
public TextView tvTitle;
public Button btnAdd;
}
}
ListItemModel:
public class ListItemModel {
String title;
public ListItemModel(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
EdittextValues:
public class EdittextValues {
int ids, etIds;
String value;
public EdittextValues(int ids, int etIds, String value) {
this.ids = ids;
this.etIds = etIds;
this.value = value;
}
public int getIds() {
return ids;
}
public void setIds(int ids) {
this.ids = ids;
}
public int getEtIds() {
return etIds;
}
public void setEtIds(int etIds) {
this.etIds = etIds;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
activity_main.xml:
<RelativeLayout 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"
tools:context=".MainActivity">
<Button
android:id="#+id/show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Values"/>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/show"
android:descendantFocusability="beforeDescendants"/>
</RelativeLayout>
list_row.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="match_parent"
android:padding="10dp">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:textSize="20dp" />
<Button
android:id="#+id/addEdittext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:layout_alignTop="#+id/title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<LinearLayout
android:id="#+id/llChild"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/addEdittext">
</LinearLayout>
</RelativeLayout>
You can solve this problem by using ExpandableListView. You can solve this problem by the reference of this link.
Related
My code java. I'm getting data from the intent as an array. I am using arraylist,listview and custom adapter. I can show the incoming data using listview. I want the item I clicked to be deleted. The name of my delete button "deleteshop" in customadapter. How can I do that ?
My code;
final ListView list = findViewById(R.id.list);
final ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>();
final String[] cartList = getIntent().getStringArrayExtra("saleData");
arrayList.add(new SubjectData("", ""));
final int cartListLength = cartList.length;
int counter = 0;
String lastItem = "";
for (String e : cartList) {
counter += 1;
if (e == "" || e == null) {
lastItem = cartList[counter-3];
break;
}
String productPhoto = "";
switch (e) {
case "1 PC GREEN COLA x 10.00 TL":
productPhoto = "cc";
break;
default:
productPhoto = "";
break; }
arrayList.add(new SubjectData(e, productPhoto));;
}
arrayList.remove(arrayList.size()-1);
arrayList.remove(arrayList.size()-1);
arrayList.add(new SubjectData("*** GRAND TOTAL TL:" + lastItem + " ***", "arrowgreen"));
arrayList.add(new SubjectData("", ""));
arrayList.add(new SubjectData("", ""));
final CustomAdapter customAdapter = new CustomAdapter(this, arrayList);
list.setAdapter(customAdapter);
SubjectData model class:
String SubjectName;
String Image;
public SubjectData(String subjectName, String image) {
this.SubjectName = subjectName;
this.Image = image;
}
Customadapter;
class CustomAdapter implements ListAdapter {
ArrayList<SubjectData> arrayList;
Context context;
public CustomAdapter(Context context, ArrayList<SubjectData> arrayList) {
this.arrayList=arrayList;
this.context=context;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return true;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final SubjectData subjectData=arrayList.get(position);
if(convertView==null){
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView=layoutInflater.inflate(R.layout.list_row, null);
TextView tittle=convertView.findViewById(R.id.title);
ImageView imag=convertView.findViewById(R.id.list_image);
ImageView
deleteshop=convertView.findViewById(R.id.deleteshop);
deleteshop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Deneme",
Toast.LENGTH_SHORT).show();
}
});
tittle.setText(subjectData.SubjectName);
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(subjectData.Image, "drawable",
context.getPackageName());
imag.setImageResource(resourceId);
}
return convertView;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return arrayList.size();
}
#Override
public boolean isEmpty() {
return false;
}
listview design;
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip">
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip">
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip" />
</LinearLayout>
<TextView
android:id="#+id/title"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:gravity="center"
android:textColor="#040404"
android:textSize="15dip"
android:textStyle="bold"
android:typeface="sans" />
<ImageView
android:layout_gravity="center"
android:id="#+id/deleteshop"
android:src="#drawable/negative"
android:layout_width="25dp"
android:layout_height="25dp" ></ImageView>
</LinearLayout>
If you want to delete clicked item from your list view then you can use this code .I tested and its deleting smoothly , after deleting its updating list also.
CustomAdapter customAdapter = new CustomAdapter(this,R.layout.list_row, arrayList);
list.setAdapter(customAdapter);
// after setting adapter put this code
// and update your ui again using set adapter
Log.e("Custom",""+arrayList.size());
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
arrayList.remove(i);
list.setAdapter(customAdapter);
}
});
This is not a best solution but ulternative , suppose if you want to update your adapter on click of deletebutton first create one interface , here is sample
public interface MyInterface{
public void deleteItem(int pos);
}
Now in your main activity use like this MainActivity extends AppCompatActivity implements MyInterface and place your interface method public void deleteItem(int pos){ arrayList.remove(pos); list.setAdapter(customAdapter); }
After that call this method from your adapter like below
deleteshop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Delete",
Toast.LENGTH_SHORT).show();
//Actually change your list of items here
if (context instanceof SampleList) {
((MainActivity)context).deleteItem(position);
}
}
});
I have an activity that retrieves data from a database that contains information (name, capital, population, flag image) for many countries. The main layout has an EditText to take the capital name as the input and a ListView. On launching the activity, all the countries are retrieved and shown briefly in the ListView. Then on typing in the EditText I want the ListView to show the countries with the matching capital name. But what I see is a blank ListView. Besides if the EditText is empty, I want the ListView to show all the countries as it showed in the beginning.
The main layout file is as below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_ad_id"
android:visibility="gone" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/adView"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp" >
<EditText
android:id="#+id/search_input_capital"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:layout_alignParentTop="true"
android:visibility="visible" >
<requestFocus />
</EditText>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#00000000"
android:divider="#android:color/transparent"
android:drawSelectorOnTop="false"
android:layout_below="#id/search_input_capital">
</ListView>
</RelativeLayout>
</RelativeLayout>
And the code for the activity ( CapitalActivity.java ) is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capital);
private ArrayList<Country> items;
private ArrayList<Country> items_all;
private ArrayList<Country> items_new;
private EfficientAdapter adapter;
private ListView listView;
EditText searchInput=(EditText)findViewById(R.id.search_input_capital);
items = new ArrayList<Country>();
items_new = new ArrayList<Country>();
listView = (ListView) findViewById(R.id.listView);
listView.setDividerHeight(10);
adapter = new EfficientAdapter(CapitalActivity.this);
listView.setAdapter(adapter);
setListItems("");
searchInput.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String searchCapital = new String(s.toString()).trim();
items_new.clear();
for(Country myCountry : items_all) {
if( myCountry.getCapital() != null &&
myCountry.getCapital().trim().toLowerCase().contains(searchCapital)) {
items_new.add(myCountry);
}
}
items.clear();
items = (ArrayList<Country>) items_new.clone();
if(searchCapital.trim().isEmpty()){
items = items_all;
}
adapter.notifyDataSetChanged();
}
});
private void setListItems(String searchKey) {
items_all= DatabaseAccessor.getCountryList(CapitalActivity.this, type, typeValue, searchKey);
items=items_all;
adapter.notifyDataSetChanged();
}
Only the necessary code segment has been shown above. What should I do to achieve the target ?
EDIT1: I mostly omitted the EfficientAdapter implementation part in the code pasted above. However I am pasting that code too this time :
public class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.country_container, null);
holder = new ViewHolder();
holder.nameView = (TextView) convertView.findViewById(R.id.nameView);
holder.continentView = (TextView) convertView.findViewById(R.id.continentView);
holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
holder.detailsView = (TextView) convertView.findViewById(R.id.detailsView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
OnClickListener ocl = new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CapitalActivity.this, CountryLearningActivity.class);
intent.putExtra(Constants.KEY_COUNTRY, items);
intent.putExtra(Constants.KEY_INDEX, position);
startActivity(intent);
}
};
Country item = items.get(position);
holder.nameView.setText(item.getCountry());
if (type.equalsIgnoreCase(filters[0]) || type.equalsIgnoreCase(filters[1])
|| type.equalsIgnoreCase(filters[2])) {
holder.continentView.setText(item.getContinent());
} else if (type.equalsIgnoreCase(filters[3])) {
holder.continentView.setText(Html
.fromHtml("Area: " + formatter.format(Double.parseDouble(item.getArea())) + " km<sup>2</sup>"));
} else if (type.equalsIgnoreCase(filters[4])) {
holder.continentView.setText("Population : " + item.getPopulation());
}
holder.imageView.setImageResource(Utils.getResID(CapitalActivity.this, item.getFlag()));
holder.detailsView.setOnClickListener(ocl);
convertView.setOnClickListener(ocl);
return convertView;
}
class ViewHolder {
TextView nameView;
ImageView imageView;
TextView continentView;
TextView detailsView;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
}
just open teh same page from your current page for the below code
enter cod protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capital);
private ArrayList<Country> items;
private ArrayList<Country> items_all;
private ArrayList<Country> items_new;
private EfficientAdapter adapter;
private ListView listView;
EditText searchInput=(EditText)findViewById(R.id.search_input_capital);
items = new ArrayList<Country>();
items_new = new ArrayList<Country>();
listView = (ListView) findViewById(R.id.listView);
listView.setDividerHeight(10);
adapter = new EfficientAdapter(CapitalActivity.this);
listView.setAdapter(adapter);
setListItems("");
searchInput.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String searchCapital = new String(s.toString()).trim();
items_new.clear();
for(Country myCountry : items_all) {
if( myCountry.getCapital() != null &&
myCountry.getCapital().trim().toLowerCase().contains(searchCapital)) {
items_new.add(myCountry);
}
}
items.clear();
items = (ArrayList<Country>) items_new.clone();
if(searchCapital.trim().isEmpty()){
items = items_all;
}
adapter.notifyDataSetChanged();
}
});
private void setListItems(String searchKey) {
items_all= DatabaseAccessor.getCountryList(CapitalActivity.this, type, typeValue, searchKey);
items=items_all;
adapter.notifyDataSetChanged();
}e here
I implemented a simple listview with an option to select each time only one item from it, this functionality is working properly.
Also I have a button for sorting the records in Asc or Desc order, when I am selecting a record and after that I am sorting the records the selector of the old record remains in the same old position, even when the selected position is updated different position.
MainActivity:
public class MainActivity extends Activity
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("abc", "defg", 1));
_data.add(new Person("aaa", "defg", 12));
_data.add(new Person("ccc", "defg", 13));
_data.add(new Person("bb", "defg", 14));
_data.add(new Person("aa", "defg", 144));
_data.add(new Person("fff", "defg", 199));
_adapter = new PersonAdapter(this, _data);
_listView.setAdapter(_adapter);
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
});
}
public static class Person
{
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String fName, String lName, int age)
{
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
}
listView adapter
public class PersonAdapter extends BaseAdapter
{
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
}
}
item layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_layout"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#drawable/list_selector"
android:weightSum="3" >
<TextView
android:id="#+id/f_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<TextView
android:id="#+id/l_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<TextView
android:id="#+id/age"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
I tried already to use clearChoices but after sorting I do not see the selector at all, also I tried to change the choise mode from single mode to none and then again single but without any success.
It is because you are switching the contents of the items inside the list item, but the click is bound to the position withing the ListView, therefore it doesn't "update" to the new position of the item.
I suggest you to programatically click on the new item when you finish the sorting.
Get the ID of the clicked item
public int getItemPosition(long id)
{
for (int position=0; position<mList.size(); position++)
if (mList.get(position).getId() == id)
return position;
return 0;
}
then after the sorting do the click
mList.performItemClick(
mList.getAdapter().getView(mActivePosition, null, null),
mActivePosition,
mList.getAdapter().getItemId(mActivePosition));
hope it helps!
I suggest to store the id of the selected item when it is selected, and after order the dataset, search for that id and re-select it.
I am trying to develop an android mobile application whereby i am required to display part of a listviews which has at least 100 items.
Now i,being the admin of a college,i has listed 100 subjects to be taught.(all to be listed in a listview.All of the subjects have a point and in order for a strudent to apply for this course he/she need to have exact of higher points.An indicative sample is below:
English:24
Spanish:16
MAths:28
Science:26
French:16
Management:22
Law:30
Asian Language:10
Now the student needs to enter his/her point and based(EXACT OR LOWER POINT)on that, he/she get the list of subjects he/she is eligible to apply for.
E.g Enter your points:24
the output in the listview should give the following:
French:16
Management:22
English:24
Asian Language:10
I tried this but am stuck and could not complete the codes:
Course.java
public class Course {
private String name;
private int points;
public Course(String name, int points) {
this.name = name;
this.points = points;
}
public String getName() {
return name;
}
public int getPoints() {
return points;
}
#Override
public String toString() {
return getName();
}
}
Course[] courses = new Course[]{
new Course("Medicine", 30),
new Course("Physics", 28),
new Course("Math", 24),
new Course("English", 20)
};
Button searchButton = (Button) findViewById(R.id.btn_search);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
List<Course> courseList = new ArrayList<Course>(Arrays.asList(courses));
// initialize the adapter with courseList... //
// this code inside the Button's onClick
int points = Integer.parseInt(editText.getText().toString());
for (Course c : courses) {
if (c.getPoints() <= points) {
adapter.add(c);
}
}
course.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_weight="1"
android:maxLines="1"
android:inputType="number"
android:layout_height="wrap_content"
android:hint="Enter your points:"
android:id="#+id/editText"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/btn_search"/>
</LinearLayout>
<ListView
android:id="#+id/courseNames"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
My solution as below -
MainActivity
public class MainActivity extends AppCompatActivity {
ListView myList;
EditText edtSearch;
Button btnSearch;
listAdapter adapter;
ArrayList<Course> alSearchCourses;
Course[] courses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.myList);
edtSearch = (EditText) findViewById(R.id.edtSearch);
btnSearch = (Button) findViewById(R.id.btnSearch);
courses = new Course[]{
new Course("Medicine", 30),
new Course("Physics", 28),
new Course("Math", 24),
new Course("English", 20)
};
adapter = new listAdapter(this, courses);
myList.setAdapter(adapter);
edtSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count == 0) {
adapter = new listAdapter(MainActivity.this, courses);
myList.setAdapter(adapter);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alSearchCourses = new ArrayList<>();
int points = Integer.parseInt(edtSearch.getText().toString());
for (int i = 0; i < courses.length; i++) {
Course c2 = courses[i];
if (c2.getPoints() <= points) {
alSearchCourses.add(c2);
}
}
Course searchCourses [] = new Course[alSearchCourses.size()];
searchCourses = alSearchCourses.toArray(searchCourses);
adapter = new listAdapter(MainActivity.this, searchCourses);
myList.setAdapter(adapter);
}
});
}
}
listAdapter
public class listAdapter extends BaseAdapter {
Context context;
Course[] courses;
LayoutInflater inflater;
public listAdapter(Context context, Course[] courses) {
this.context = context;
this.courses = courses;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return courses.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(R.layout.list_item_layout, null);
}
TextView txtCourse = (TextView) convertView.findViewById(R.id.txtCourse);
txtCourse.setText(courses[position].getName() + "-" + courses[position].getPoints());
return convertView;
}
}
Hope it helps :)
I want to add quantity when the add button is clicked and subtract quantity when sub button is clicked here i am not showing my setter/getter class(RowItem) and my xml files
(main.xml,item_details_view)
This is my Adapter class
public class ItemListBaseAdapter extends ArrayAdapter<RowItem> {
Context context;
public ItemListBaseAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
Button add,sub;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_details_view, 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);
holder.add = (Button) convertView
.findViewById(R.id.button1);
holder.sub = (Button) convertView
.findViewById(R.id.button2);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
holder.add.setTag(position);
holder.sub.setTag(position);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Adds 1 to the counter
int counter=0;
counter = counter + 1;
}
});
holder.sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Subtract 1 from counter
int counter=0;
counter = counter - 1;
}
});
return convertView;
}
}
Thisi is my Activity class
public class ListViewImagesActivity extends Activity implements
OnItemClickListener {
public static final String[] titles = new String[] { "EggBurger",
"cheesBurger", "KingBurger", "Mixed" };
public static final String[] descriptions = new String[] {"Select 0 Item"
};
public static final Integer[] images = { R.drawable.burger1,
R.drawable.burger2, R.drawable.burger3, R.drawable.burger4 };
ListView listView;
List<RowItem> rowItems;
Button add,sub;
int counter=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[0]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list);
ItemListBaseAdapter adapter = new ItemListBaseAdapter(this,
R.layout.item_details_view, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
this is my RowItem 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;
}
}
this is my main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
this is my item_details_view
<?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: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" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button2"
android:layout_marginRight="16dp"
android:layout_toLeftOf="#+id/button2"
android:text="Add" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/desc"
android:layout_alignParentRight="true"
android:text="Sub" />
</RelativeLayout>
First of all, if you want to change the quantity value, you should have a variable representing quantity which you can change. You have included quantity value in the description text, which is bad design. What you should do is have a quantity variable int in the RowItem class as shown. You desc should just return a string from the quantity value as shown:
public class RowItem {
private int imageId;
private String title;
private int quantity = 0;
public RowItem(int imageId, String title, int quantity) {
this.imageId = imageId;
this.title = title;
this.quantity = quantity;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return "Select " + quantity + " Item";
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public String toString() {
return title + "\n" + quantity;
}
}
In your activity, instead of storing descriptions, store quantities:
public static final int[] quantities = new int[]{ 0 };
In onCreate initialize the rowItems as follows
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], quantities[0]);
rowItems.add(item);
}
Finally, in your OnClickListener, get the quantity value, update it and set the new description.
final ViewHolder viewHolderFinal = holder;
final RowItem finalRowItem = rowItem;
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = finalRowItem.getQuantity(); // get the quantity for this row item
finalRowItem.setQuantity(quantity + 1); // update it by adding 1
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc()); // set the new description (that uses the updated qunatity)
}
});
holder.sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = finalRowItem.getQuantity(); // get the quantity for this row item
finalRowItem.setQuantity(quantity - 1); // update it by subtracting 1
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc()); // set the new description (that uses the updated qunatity)
}
});
*Note: * I have compiled and run this code. So if you do everything as I mentioned it will work.