Dynamically adding listitems to baseadapter an android - java

I want to dynamically add new listitems by pressing a button.but i don't no the right way to do this.
BaseAdapter
public class CompetitionResultListAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<Result> result;
DataManager datamanager;
#Override
public int getCount() {
return result!=null ? result.size() : 0;
}
#Override
public Object getItem(int position) {
return result.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
// inflate the layout
LayoutInflater inflater = activity.getLayoutInflater();
convertView = inflater.inflate(R.layout.list_item_competition_result, parent, false);
}
EditText listItemDate = (EditText) convertView.findViewById(R.id.date);
EditText listItemPlace = (EditText) convertView.findViewById(R.id.place);
EditText listItemComment = (EditText) convertView.findViewById(R.id.comment);
result.get(position).setDate(listItemDate.getText().toString());
result.get(position).setPlace(listItemPlace.getText().toString());
result.get(position).setComment(listItemComment.getText().toString());
return convertView;
}
public void refreshResultList(ArrayList<Result> result){
this.result = result;
notifyDataSetChanged();
}
}
java class
public class AddCompetitionResult extends Fragment {
private CompetitionResultListAdapter competitionResultListAdapter;
private DataManager datamanager;
ArrayList<Result> result;
ListView listView;
private Horse horse;
private Button addResults;
int clickCounter=0;
public AddHorseCompetitionResult(Horse horse) {
this.horse = horse;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_horse_competition_result,
null);
addResults = (Button) view.findViewById(R.id.btn_add_competition_result);
listView = (ListView) view.findViewById(R.id.data_list);
// result = datamanager.create(getActivity());
competitionResultListAdapter = new CompetitionResultListAdapter();
View footerView = ((LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.competition_result_listview_footer, null, false);
listView.addFooterView(footerView);
listView.setAdapter(competitionResultListAdapter);
addResults.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String resultId = null;
// result.add();
competitionResultListAdapter.notifyDataSetChanged();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (competitionResultListAdapter.getCount() == position) {
MainActivity mainActivity = MainActivity.getInstance();
mainActivity.setFragment(new AddHorseDetailedInfo(horse),
"Add horse more info");
// datamanager.createResult(result);
} else {
// ContactGroup cg = (ContactGroup)
// competitionResultListAdapter.getItem(position);
// MainActivity mainActivity = MainActivity.getInstance();
// mainActivity.setFragment(new
// ContactListView(cg.getGroupId()), "contacts");
}
}
});
return view;
}
}

// on button CLick
{
// toast a meesaage here : onClick()
result.add(urObject)// simply put create a object of ur result type and put "" values
// finallly call notifyDataSetChanged on adapter
adapter.notifyDataSetChanged();
}

Tryt to replace your adapter code with this.
public class CompetitionResultListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<Result> result;
DataManager datamanager;
#Override
public int getCount() {
return result!=null ? result.size() : 0;
}
#Override
public Object getItem(int position) {
return result.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(activity).inflate(R.layout.list_item_competition_result, null, false);
holder.listItemDate = (EditText) convertView.findViewById(R.id.date);
holder.listItemPlace = (EditText) convertView.findViewById(R.id.place);
holder.listItemComment = (EditText) convertView.findViewById(R.id.comment);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.listItemDate = (EditText) convertView.findViewById(R.id.date);
holder.listItemPlace = (EditText) convertView.findViewById(R.id.place);
holder.listItemComment = (EditText) convertView.findViewById(R.id.comment);
result.get(position).setDate(listItemDate.getText().toString());
result.get(position).setPlace(listItemPlace.getText().toString());
result.get(position).setComment(listItemComment.getText().toString());
return convertView;
}
class ViewHolder {
EditText listItemDate;
EditText listItemPlace;
EditText listItemComment;
}
public void refreshResultList(ArrayList<Result> result){
this.result = result;
notifyDataSetChanged();
}
}

Related

How do I send the text of the ListView item that was clicked to my new activity?

I would like someone to click on an item in my ListView and then my new activity would start and the text of the item they clicked on should be set as the text of the TextView in my new activity. Currently with the following code, my TextView result is:
'com.example.draft.AnimalNames#31571cf'
Here is what I have in MainActivity.java:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String clickedName = (list.getItemAtPosition(position).toString());
Intent intent = new Intent(MainActivity.this, Profile.class);
intent.putExtra("clickedName", clickedName);
startActivity(intent);
System.out.println(clickedName);
}
});
And in my new activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_layout);
Intent intent = getIntent();
String clickedName = intent.getStringExtra("clickedName");
animalName = findViewById(R.id.textView);
animalName.setText(clickedName);
}
And in my AnimalNames.java file:
public class AnimalNames {
private String animalName;
public AnimalNames(String animalName) {
this.animalName = animalName;
}
public String getanimalName() {
return this.animalName;
}
}
I don't think it's relevant to my question but here is my ListViewAdapter.java file:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<AnimalNames> animalNamesList; // Declare a null variable
private ArrayList<AnimalNames> arraylist; // Declare a null array
public ListViewAdapter(Context context, List<AnimalNames> animalNamesList) {
mContext = context;
this.animalNamesList = animalNamesList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<AnimalNames>();
this.arraylist.addAll(animalNamesList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return animalNamesList.size();
}
#Override
public AnimalNames getItem(int position) {
return animalNamesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_view_items, null); // Locate the TextViews in list_view_items.xml
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.name.setText(animalNamesList.get(position).getanimalName());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
animalNamesList.clear();
if (charText.length() == 0) {
animalNamesList.addAll(arraylist);
} else {
for (AnimalNames wp : arraylist) {
if (wp.getanimalName().toLowerCase(Locale.getDefault()).contains(charText)) {
animalNamesList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
String clickedName = (list.getItemAtPosition(position).toString());
By calling toString() method, it will give you the object reference, which is what you get in the TextView.
According to your code, if you wish to see the Animal name, you should do (and fix the method name to getAnimalName):
String clickedName = ((AnimalNames)list.getItemAtPosition(position)).getanimalName();
getItemAtPosition() returns an Object, so you need to cast it to the correct class.

how to access the elements of another layout?

I created listView. enter image description here
And my adapter, which has a button, textView.enter image description here
I want to when i click on an button was removed element from the list.
How in the class MainActiviti access to the elements of another layout?
public class AdapterItem extends BaseAdapter {
Context context;
LayoutInflater lInflater;
ArrayList<ItemInList> items;
public AdapterItem(Context context, ArrayList<ItemInList> items){
this.context = context;
this.items = items;
lInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
ItemInList itemInList = getItemList(position);
((TextView) view.findViewById(R.id.id_item)).setText(itemInList.id);
((TextView) view.findViewById(R.id.name)).setText(itemInList.name);
((ImageButton) view.findViewById(R.id.imageButton)).setImageResource(itemInList.imageButton);
return view;
}
ItemInList getItemList(int position) {
return ((ItemInList) getItem(position));
}
}
ItemInList.java
public class ItemInList {
String name;
String id;
int imageButton;
boolean deleteChek;
public ItemInList(String name, String id, int imageButton, boolean deleteChek){
this.name = name;
this.id = id;
this.imageButton = imageButton;
this.deleteChek = deleteChek;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ArrayList<ItemInList> arrayItemInLists = new ArrayList<ItemInList>();
AdapterItem adapterItem;
ListView listViewl;
Button delete;
Button checkAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fillData();
listViewl = (ListView) findViewById(R.id.listView);
delete = (Button) findViewById(R.id.delete_select);
checkAll = (Button) findViewById(R.id.select_all);
adapterItem = new AdapterItem(this, arrayItemInLists);
listViewl.setAdapter(adapterItem);
}
public void fillData() {
for (int i = 1; i <= 20; i++) {
arrayItemInLists.add(new ItemInList("String" + i," " + i, R.drawable.delete,false));
}
}
You need just remove an item from your DATA (in your case - arrayItemInLists) and call notifyDataSetChanged(). In fact you can do that inside an Adapter.
private OnClickListener listener= new OnClickListener() {
#Override
public void onClick(View v) {
int position = ((Integer) v.getTag());
}
};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
ItemInList itemInList = getItemList(position);
((TextView) view.findViewById(R.id.id_item)).setText(itemInList.id);
((TextView) view.findViewById(R.id.name)).setText(itemInList.name);
((ImageButton) view.findViewById(R.id.imageButton)).setImageResource(itemInList.imageButton);
((ImageButton) view.findViewById(R.id.imageButton)).setTag(position);
((ImageButton) view.findViewById(R.id.imageButton)).setOnClickListener(listener);
return view;
}

How to implement a ListView in a Fragment in Android

I have Fragment.java and its XML. In XML I put ListView and I want to update the ListView in Fragment and add some String.
I am trying to make a custom adapter. When I run the ListView in Activity with custom adapter all works great, but when I put the same code in Fragment nothing happens. I am using EventBus3.
This is my Activity send Event
EventBus.getDefault().post(new SendDataHelper(nameOfItem[myItemInt]));
This is my Fragment:
public class MyOrderFragment extends Fragment {
TextView name;
ListView listOrder;
private Context context;
List<cources> collegeList;
public MyOrderFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
#Subscribe
public void onMessageEvent(SendDataHelper event){
Toast.makeText(getActivity(), event.getText(), Toast.LENGTH_SHORT).show();
String text = event.getText();
name.setText(text);
cources college;
collegeList = new ArrayList<cources>();
college = new cources();
college.name = "sharon";
collegeList.add(college);
listOrder.setVisibility(View.VISIBLE);
ListAdapter adapter = new ListAdapter(collegeList, context);
listOrder.setAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_order_fragment, container, false);
name = (TextView) rootView.findViewById(R.id.textView);
listOrder = (ListView) rootView.findViewById(R.id.listOrder);
return rootView;
}
}
This is my adapter
public class ListAdapter extends BaseAdapter
{
Context context;
List<cources> valueList;
public ListAdapter(List<cources> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
}
#Override
public int getCount()
{
return this.valueList.size();
}
#Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
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.txtNamePlanche = (TextView)convertView.findViewById(R.id.Tx_name_planche);
viewItem.txtPriceBaget = (TextView)convertView.findViewById(R.id.Tx_price_baget);
viewItem.txtPricePlate = (TextView)convertView.findViewById(R.id.Tx_price_plate);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.txtNamePlanche.setText(valueList.get(position).name);
viewItem.txtPriceBaget.setText(valueList.get(position).price_baget);
viewItem.txtPricePlate.setText(valueList.get(position).price_plate);
return convertView;
}
}
This is my ItemView
import android.widget.TextView;
class ViewItem
{
TextView txtNamePlanche;
TextView txtPricePlate;
TextView txtPriceBaget;
}
This is cources:
public class cources
{
public String name;
public String price_plate;
public String price_baget;
}
Change extends Fragment to extends ListFragment

Android: How to setTag with Adapter

I have following situation: I have PostBaseAdapter where I initialize my views and MainActivity where I want to set Checkbox with switch parameter by getTag() but I don't know how to setTag() for my checkbox and where.
public class PostBaseAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private ArrayList<PostValue> postValueArrayList;
public PostBaseAdapter(Context context, ArrayList<PostValue> postValueArrayList) {
this.layoutInflater = LayoutInflater.from(context);
this.postValueArrayList = postValueArrayList;
}
#Override
public int getCount() {
return postValueArrayList.size();
}
#Override
public PostValue getItem(int position) {
return postValueArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item_post, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
PostValue postValue = getItem(position);
viewHolder.tvTitle.setText(postValue.getBrand());
viewHolder.tvPublishDate.setText(postValue.getDate());
viewHolder.cost.setText(postValue.getPrice());
viewHolder.descriptionOfItem.setText(postValue.getDescription());
viewHolder.deliveryTime.setText("Cрок доставки: "+postValue.getDeliveryTime()+" дней");
viewHolder.checkBox.setChecked(false);
return convertView;
}
private class ViewHolder {
Button order;
CheckBox checkBox;
TextView tvTitle, tvPublishDate, cost, deliveryTime, descriptionOfItem;
public ViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
tvPublishDate = (TextView) item.findViewById(R.id.tvPublishDate);
cost = (TextView) item.findViewById(R.id.cost);
deliveryTime = (TextView) item.findViewById(R.id.delivery_time);
descriptionOfItem = (TextView) item.findViewById(R.id.description);
checkBox = (CheckBox) item.findViewById(R.id.checkbox);
order = (Button) item.findViewById(R.id.order);
}
}
}
and MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
order = (Button) findViewById(R.id.order);
checkbox = (CheckBox) findViewById(R.id.checkbox);
lvPcsPost = (ListView) findViewById(R.id.lvPcsPost);
lvPcsPost.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lvPcsPost.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (postValueArrayList != null && postValueArrayList.size() > 0) {
}
}
});
new PostAsync().execute();
//Установка Статус Бара определенного цвета
Window window = this.getWindow();
window.setStatusBarColor(this.
getResources().getColor(R.color.colorPrimary));
Paper.init(this);
}
class PostAsync extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
XMLHelper helper;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "Загрузка", "Ждите, идет загрузка автозапчастей ...", true, false);
}
#Override
protected Void doInBackground(Void... arg0) {
helper = new XMLHelper();
helper.get(getIntent().getStringExtra("level")); // Передаем Интент с артикулом из поиска
postValueArrayList = helper.getPostsList();
return null;
}
#Override
protected void onPostExecute(Void result) {
PostBaseAdapter postBaseAdapter = new PostBaseAdapter(MainActivity.this, postValueArrayList);
lvPcsPost.setAdapter(postBaseAdapter);
pd.dismiss();
}
}
public void checkBoxClick(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getTag().toString()) {
case "0":
if (checked) {
Toast.makeText(this, "ЩЕЛК:", Toast.LENGTH_LONG).show();
}
break;
}
}

why is notifyDataSetChanged() not working in my code?

Why is my code not working? I have already tried using notifyDataSetChanged(), or using invalid() for my listview, or using .setAdapter() again for my adapter, but its still not working please help me.
public class ListDel extends Activity{
ListView mylist_del;
ListViewAdapter listViewAdapter_del;
TypedArray images_del;
ImageView bin_image;
private static String[] names, ages;
storageListImplementation lists = new storageListImplementation();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.del_layout);
names = lists.getNames();
ages = lists.getAges();
images_del = getResources().obtainTypedArray(R.array.icons);
bin_image = (ImageView)findViewById(R.id.del_image_icon);
listViewAdapter_del = new ListViewAdapter(this);
mylist_del = (ListView)findViewById(R.id.listview_delete);
mylist_del.setAdapter(listViewAdapter_del);
}
private class ListViewAdapter extends BaseAdapter{
private LayoutInflater mInflater;
public ListViewAdapter(Context context){
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return names.length;
}
public Object getItem(int pos) {
return pos;
}
public long getItemId(int position) {
return position;
}
private OnClickListener binClick(ImageView img, final int position, String name) {
return new View.OnClickListener(){
public void onClick(View v) {
lists.del(names[position]);
mylist_del.invalidate();
//mylist_del.setAdapter(listViewAdapter_del);
listViewAdapter_del.notifyDataSetInvalidated();
listViewAdapter_del.notifyDataSetChanged();
//newlistviewadap();
//mylist_del.setAdapter(new ListViewAdapter(this));
//listViewAdapter_del.notifyDataSetChanged();
//String addSuccessful = "You have successfully deleted "+names[position]+" and his/her information in you database";
//Toast.makeText(getApplicationContext(), addSuccessful, Toast.LENGTH_LONG).show();
//ListDel.this.finish();
}
};
}
public void newlistviewadap(){
mylist_del.setAdapter(listViewAdapter_del);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder textView;
if(convertView==null){
convertView = mInflater.inflate(R.layout.del_listview_row, null);
textView = new ViewHolder();
textView.text = (TextView) convertView.findViewById(R.id.del_values_row);
textView.age = (TextView) convertView.findViewById(R.id.del_age_row);
textView.image = (ImageView) convertView.findViewById(R.id.del_image);
textView.delbutton = (ImageView) convertView.findViewById(R.id.del_image_icon);
convertView.setTag(textView);
}else{
textView = (ViewHolder) convertView.getTag();
}
textView.text.setText(names[position]);
textView.age.setText(ages[position]);
textView.image.setImageDrawable(images_del.getDrawable(position));
textView.delbutton.setOnClickListener(binClick( textView.delbutton, position, names[position]));
return convertView;
}
}
static class ViewHolder{
TextView text;
TextView age;
ImageView image;
ImageView delbutton;
}
}
Try removing
listViewAdapter_del.notifyDataSetInvalidated();
Once you've called it, mylist_del will not retrieve more data from listViewAdapter_del, so only keep the code below and try again:
lists.del(names[position]);
listViewAdapter_del.notifyDataSetChanged();

Categories