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();
Related
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.
I have two different card view in one layout. I need that The latest news is added to one card view, and the rest in another. For exapmle, on image
MyRecyclerAdapter code
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.CustomViewHolder> {
private List<FeedItem> feedItemList;
private Context mContext;
public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
FeedItem feedItem = feedItemList.get(i);
//Download image using picasso library
Picasso.with(mContext).load(feedItem.getThumbnail())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(customViewHolder.imageView);
//Setting text view title
customViewHolder.textView.setText(Html.fromHtml(feedItem.getTitle()));
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
CustomViewHolder holder = (CustomViewHolder) view.getTag();
int position = holder.getPosition();
FeedItem feedItem = feedItemList.get(position);
Toast.makeText(mContext, feedItem.getTitle(), Toast.LENGTH_SHORT).show();
}
};
//Handle click event on both title and image click
customViewHolder.textView.setOnClickListener(clickListener);
customViewHolder.imageView.setOnClickListener(clickListener);
customViewHolder.textView.setTag(customViewHolder);
customViewHolder.imageView.setTag(customViewHolder);
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
protected ImageView imageView;
protected TextView textView;
public CustomViewHolder(View view) {
super(view);
this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
this.textView = (TextView) view.findViewById(R.id.title);
}
}
}
The approach I would use if I were in you, to accomplish what you posted in the picture is to override getItemViewType and have two different types of ViewHolder, once for the header, the one with the big image and the other adapter for the small rows. onBindViewHolder gets the type as parameter. In your case is int i.
I write a quickdemo like this:
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList mData = new ArrayList();
private LayoutInflater mInflater;
private TreeSet mSeparatorSet = new TreeSet();
public MyCustomAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparator(String item) {
mData.add(item);
mSeparatorSet.add(mData.size() - 1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return mSeparatorSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView + "type " + type);
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.item1, null);
holder.textView = (TextView) convertView.findViewById(R.id.text_view);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.item2, null);
holder.textView = (TextView) convertView.findViewById(R.id.textSeparator);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(mData.get(position) + "");
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
or if you want to use header and footer, create headerView layout:
View header = (View) getLayoutInflater().inflate(R.layout.headerView,null);
listView.addHeaderView(header);
In my app I have PostersFragment that will be a GridView with movies posters, in this fragment I need to initialize the GridView and customGridViewAdapter.
My customGridViewAdapter need to get the Bitmaps array and then work with it.
The problem that I call to AsyncTask that is in different class that gets all information from JSON and stores the information with the movies posters on local database.
I cant understand how and when to use the .setAdapter(gridViewCustomAdapter);
There is my code.
public class PostersFragment extends Fragment implements AdapterView.OnItemClickListener {
private GridView gv_posters;
private GridViewCustomAdapter gridViewCustomAdapter;
public PostersFragment() {
setHasOptionsMenu(true);
}
#Override
public void onStart() {
super.onStart();
UpdatePosters();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("TESTAG","onCreateView");
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
gv_posters = (GridView) rootView.findViewById(R.id.gv_posters);
gv_posters.setAdapter(gridViewCustomAdapter);
gv_posters.setOnScrollListener(new PostersScrollListener(getActivity().getApplicationContext()));
gv_posters.setOnItemClickListener(this);
// Define new adapter for grid view
return rootView;
}
private void UpdatePosters() {
Log.d("TESTAG","UpdatePoster");
MoviesTask task = new MoviesTask(getActivity(),gridViewCustomAdapter);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String path = prefs.getString(getString(R.string.sort_method_posters_pref), getString(R.string.default_path));
task.execute(path);
}
MoviesTask.java
public class MoviesTask extends AsyncTask<String, Void, Bitmap[]> {
// Byte array to handle bitmaps
private byte[] imgByte;
// Context and custom adapter variables
private final Context mContext;
private GridViewCustomAdapter mGridCustomAdapter;
// MovieTask Constructor
public MoviesTask(Context context, GridViewCustomAdapter gridAdapter) {
mContext = context;
mGridCustomAdapter = gridAdapter;
}
Parsing JSON methods...
#Override
protected void onPostExecute(Bitmap[] bitmaps){
Log.d("TESTAG","onPostExecute");
if (bitmaps != null)
mGridCustomAdapter = new GridViewCustomAdapter(mContext,R.id.single_gv_poster,bitmaps);
}
GridViewCustomAdapter.java
public class GridViewCustomAdapter extends BaseAdapter{
private Context context;
int layoutResource;
private Bitmap[] bitmaps;
public GridViewCustomAdapter(Context context,int layoutResource, Bitmap[] bitmaps){
this.context = context;
this.layoutResource = layoutResource;
this.bitmaps = bitmaps;
}
#Override
public int getCount() {
return 0;
}
#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) {
View view = convertView;
viewHolder holder = null;
if (view == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
view = inflater.inflate(layoutResource,parent,false);
holder = new viewHolder();
holder.imageView = (ImageView)view.findViewById(R.id.single_gv_poster);
view.setTag(holder);
}else
holder = (viewHolder)view.getTag();
Bitmap bitmap = bitmaps[position];
holder.imageView.setImageBitmap(bitmap);
return view;
}
static class viewHolder{
ImageView imageView;
}
}
Anyone can help me with this issue please?
You can do this way:
Delete line from onCreate():
gv_posters.setAdapter(gridViewCustomAdapter);
Your PostExecute should looks like this:
#Override
protected void onPostExecute(Bitmap[] bitmaps){
Log.d("TESTAG","onPostExecute");
if (bitmaps != null)
mGridCustomAdapter = new GridViewCustomAdapter(mContext,R.id.single_gv_poster,bitmaps);
gv_posters.setAdapter(mGridCustomAdapter);
}
}
Hope this will help you.
I am trying to design a menu like this:
It almost works, however there is a problem. The menu works fine at start, but after scrolling down and up again, the items are gone and downloaded again and it takes a little time. Is there a way to set a number of elements to create at start and keep them from disappearing?
Here is my code:
public class MyActivity extends Activity implements AdapterView.OnItemClickListener {
String headers[];
String image_urls[];
List<MyMenuItem> menuItems;
ListView mylistview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
menuItems = new ArrayList<MyMenuItem>();
headers = getResources().getStringArray(R.array.header_names);
image_urls = getResources().getStringArray(R.array.image_urls);
for (int i = 0; i < headers.length; i++) {
MyMenuItem item = new MyMenuItem(headers[i], image_urls[i]);
menuItems.add(item);
}
mylistview = (ListView) findViewById(R.id.list);
MenuAdapter adapter = new MenuAdapter(this, menuItems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(this);
}
}
public class MyMenuItem {
private String item_header;
private String item_image_url;
public MyMenuItem(String item_header, String item_image_url){
this.item_header=item_header;
this.item_image_url=item_image_url;
}
public String getItem_header(){
return item_header;
}
public void setItem_header(String item_header){
this.item_header=item_header;
}
public String getItem_image_url(){
return item_image_url;
}
public void setItem_image_url(String item_image_url){
this.item_image_url=item_image_url;
}
}
public class MenuAdapter extends BaseAdapter{
Context context;
List<MyMenuItem> menuItems;
MenuAdapter(Context context, List<MyMenuItem> menuItems) {
this.context = context;
this.menuItems = menuItems;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return menuItems.get(position);
}
#Override
public long getItemId(int position) {
return menuItems.indexOf(getItem(position));
}
private class ViewHolder {
ImageView ivMenu;
TextView tvMenuHeader;
}
#Override
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.menu_item, null);
holder = new ViewHolder();
holder.tvMenuHeader = (TextView) convertView.findViewById(R.id.tvMenuHeader);
holder.ivMenu = (ImageView) convertView.findViewById(R.id.ivMenuItem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MyMenuItem row_pos = menuItems.get(position);
Picasso.with(context)
.load(row_pos.getItem_image_url())
// .placeholder(R.drawable.empty)
// .error(R.drawable.error)
.into(holder.ivMenu);
holder.tvMenuHeader.setText(row_pos.getItem_header());
Log.e("Test", "headers:" + row_pos.getItem_header());
return convertView;
}
}
Possibly you can implement lazy loading with some sort of caching of images or whatever you are downloading...
You say the images are donwloaded, i assume that the images are coming from internet. Implement a custom cache for http download or download and store the images in one place before you use
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();
}
}