Listview show only last item over and over - java

I am new to android development. I enrolled Udacity course and I get to where I have to use a costume arrayAdapter to display a listView of data (text) I nailed most of it but i have a problem with data displayed which is : when I launch my activity listView displays last item on may arraylist
i have tried almost everything out their nothing worked for me
My Data
/**
* Displays text to the user.
*/
public class Numbers {
//First we Set the Stat of our Class :
// English Translation
public static String englishTranslation;
//Tamazight Translation
public static String tamazightTranslation;
/**
* Create a new Numbers Object :
*
* #param englishTranslation is for ENGLISH NUMBERS
* #param tamazightTranslation is for TAMAZIGHT NUMBERS
*/
//Constructor
public Numbers(String englishTranslation, String tamazightTranslation) {
this.englishTranslation = englishTranslation;
this.tamazightTranslation = tamazightTranslation;
}
//Getter
public static String getEnglishTranslation() {
return englishTranslation;
}
public static String getTamazightTranslation() {
return tamazightTranslation;
}
}
My ArrayList :
public class ActivityNumbers extends AppCompatActivity {
//Add English numbers to The ARRAYList
ArrayList<Numbers> englishNumbers = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numbers);
englishNumbers.add(new Numbers("One", "Yan"));
englishNumbers.add(new Numbers("Two", "Sin"));
englishNumbers.add(new Numbers("Three", "Krad"));
englishNumbers.add(new Numbers("Four", "Koz"));
englishNumbers.add(new Numbers("Five", "Smos"));
englishNumbers.add(new Numbers("Six", "Sdis"));
englishNumbers.add(new Numbers("Seven", "Sa"));
englishNumbers.add(new Numbers("Eight", "Tam"));
englishNumbers.add(new Numbers("Nine", "Tza"));
englishNumbers.add(new Numbers("Ten", "Mraw"));
//EnglishNumbers.remove(0);
//EnglishNumbers.size();
// EnglishNumbers.get(1);
//Create a NEW TV object
/**Creating an ArrayAdapter (DATA HOLDER)
#param Context / the ACTIVITY concerned
#param Android.R.layout : an XML layout file contains TextView predefined by Android
#param Items to display */
NumbersAdapter itemsAdapter = new NumbersAdapter (this, englishNumbers);
// Linking the ListView object to a Variable
ListView numbersListView = (ListView) findViewById(R.id.list);
//Calling setAdapter Method on numbersListView with "itemsAdapter
numbersListView.setAdapter(itemsAdapter);
}
}
My Adapter :
public class NumbersAdapter extends ArrayAdapter<Numbers> {
public NumbersAdapter(Context context, ArrayList<Numbers> englishNumbers) {
super(context, 0, englishNumbers);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.listitem, parent, false);
}
Numbers numbers = getItem(position);
System.out.println(position);
TextView tamazight_item = (TextView) listItemView.findViewById(R.id.tamazight_item);
TextView english_item = (TextView) listItemView.findViewById(R.id.english_item);
tamazight_item.setText(numbers.getEnglishTranslation());
System.out.println(numbers.getEnglishTranslation());
english_item.setText(numbers.getTamazightTranslation());
System.out.println(numbers.getTamazightTranslation());
return listItemView;
}
}

try this way
Context context;
ArrayList<Numbers> englishNumbers;
public NumbersAdapter(Context context, ArrayList<Numbers> englishNumbers)
{
this.context=context;
this.englishNumbers=englishNumbers;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
convertView= LayoutInflater.from(context).inflate(R.layout.listitem,parent,false);
TextView tamazight_item = (TextView) listItemView.findViewById(R.id.tamazight_item);
TextView english_item = (TextView) listItemView.findViewById(R.id.english_item);
tamazight_item.setText(englishNumbers.get(position).getEnglishTranslation());
english_item.setText(englishNumbers.get(position).getTamazightTranslation());
return convertView;
}
And not forgot to make NumbersAdapter extends BaseAdapter

Your tamazightTranslation and englishTranslation attributes are static on the Numbers class meaning that, those are class attributes. Remove static from the variables and from the getters and you should be fine. See the difference between class attributes and instance attributes here https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

I have changed your model class and Adapter class please follow this It will work
public class Numbers {
//First we Set the Stat of our Class :
// English Translation
private String englishTranslation;
//Tamazight Translation
private String tamazightTranslation;
public String getEnglishTranslation() {
return englishTranslation;
}
public void setEnglishTranslation(String englishTranslation) {
this.englishTranslation = englishTranslation;
}
public String getTamazightTranslation() {
return tamazightTranslation;
}
public void setTamazightTranslation(String tamazightTranslation) {
this.tamazightTranslation = tamazightTranslation;
}
}
Adapter Class
public class NumbersAdapter extends ArrayAdapter<Numbers> {
private Context mContext;
private ArrayList<Numbers>list;
public NumbersAdapter(Context context, ArrayList<Numbers> englishNumbers) {
super(context, 0, englishNumbers);
this.mContext=context;
this.list = englishNumbers;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(mContext).inflate(R.layout.listitem, parent, false);
}
Numbers numbers = list.get(position);
System.out.println(position);
TextView tamazight_item = (TextView) listItemView.findViewById(R.id.tamazight_item);
TextView english_item = (TextView) listItemView.findViewById(R.id.english_item);
tamazight_item.setText(numbers.getEnglishTranslation());
System.out.println(numbers.getEnglishTranslation());
english_item.setText(numbers.getTamazightTranslation());
System.out.println(numbers.getTamazightTranslation());
return listItemView;
}
}

If it is showing one last item in your listview, there might be several reasons for that.
You need to override getCount() in ArrayAdapter to have size of the list. It may fix the problem.
Make sure, the list view is not declared inside scrollview in your xml layout. If it is, handle it properly using nestedscrollview or else.
If it is showing the same data in all rows of your list view, then it might be
In your case, you need to remove static keywords in front of properties, static means that properties or methods belong to Number class, not to the instance of your Number class object. Basically, it must be the reason.

Related

Can't put an ArrayList in a ListView inside a CustomAdapter in Android Studio

I'm having a problem understanding how to finish this part of my code.
It's an app that searches a list of games with the help of an API.
Everything is working so far so good right now, but one final thing.
In the code, first of all I have a simple activity with an edit_text, a button and an empty list view that it is called "lv_listofgames".
Then, when I press the "search" button, I fill the "lv_listofgames" with a series of rows formed by an imageview, a listView called "list_item_text" and a button.
To this point everything is okay it seems.
Then I should just fill the "list_item_text" inside the "lv_listofgames" with the contents of an arraylist but I just can't make it happen. I tried in many ways but I'm stuck. I even tried using 2 adapters but the app crashed everytime or the "list_item_text" remained empty.
The arrayList is something like: [game_title='Name', release_date='date', platform=platform]
I seem so close to the solution but I just can't figure it out how to accomplish that. Im going crazy :(
tl;dr: problem: when I press the "search" button the arrayList content doesn't appear in the ListView "list_item_text".
Here is the code, tell me if something is wrong, thanks:
public class MainActovity extends AppCompatActivity {
EditText et_searchName;
Button btn_search;
ListView lv_listofgames;
ListView lv;
final GamesDataService gameDataService = new GamesDataService(MainActovity.this);
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
et_searchName = findViewById(R.id.et_searchName);
btn_search = findViewById(R.id.btn_search);
lv_listofgames= findViewById(R.id.lv_listofgames);
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gameDataService.getGameName(et_searchName.getText().toString(), new GamesDataService.searchGamesResponse() {
#Override
public void onError(String message) {
Toast.makeText(MainActovity.this, "Error", Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(List<GamesReportModel> gamesReportModels) {
List<GamesReportModel> newName = gamesReportModels;
List<String> stringsList = new ArrayList<>(newName.size());
for (Object object : newName) {
stringsList.add(Objects.toString(object, null));
}
System.out.println("stringsList:" + stringsList);
lv = (ListView) findViewById(R.id.lv_listofnames);
MyListAdapter adapter = new MyListAdapter(MainActovity.this, R.layout.details, stringsList);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
}
});
}
class MyListAdapter extends ArrayAdapter<String> {
private int layout;
public MyListAdapter(#NonNull Context context, int resource, #NonNull List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
MainActovity.ViewHolder mainViewHolder = null;
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
MainActovity.ViewHolder viewHolder = new MainActovity.ViewHolder();
viewHolder.thumbnail = (ImageView) convertView.findViewById(R.id.list_item_thumbnail);
viewHolder.title = (ListView) convertView.findViewById(R.id.list_item_text);
viewHolder.button = (Button) convertView.findViewById(R.id.list_item_btn);
convertView.setTag(viewHolder);
viewHolder.button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
else {
mainViewHolder = (MainActovity.ViewHolder) convertView.getTag();
}
return convertView;
}
}
public class ViewHolder {
ImageView thumbnail;
ListView title;
Button button;
}
}
GamesReportModel:
public class GamesReportModel {
private String game_title;
private String release_date;
private String platform;
public GamesReportModel(String game_title, String release_date, String platform) {
this.game_title = game_title;
this.release_date = release_date;
this.platform = platform;
}
public GamesReportModel() {
}
#Override
public String toString() {
return "game_title='" + game_title + '\'' +
", release_date='" + release_date + '\'' +
", platform=" + platform;
}
public String getGame_title() {
return game_title;
}
public void setGame_title(String game_title) {
this.game_title = game_title;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
}
There are two things you need to change in your code to get the desired effect.
In your row view layout (R.layout.details), replace the ListView with a TextView since you are just trying to show text for a given row (not a nested list inside each row). Then update the view holder to hold the correct view type as well
viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_text);
//...
public class ViewHolder {
ImageView thumbnail;
TextView title;
Button button;
}
In the adapter's getView method you have to actually set the text to show for that row. You never set the text to show anywhere, which is why your rows are blank. That should look like this:
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
MainActovity.ViewHolder mainViewHolder = null;
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
MainActovity.ViewHolder viewHolder = new MainActovity.ViewHolder();
viewHolder.thumbnail = (ImageView) convertView.findViewById(R.id.list_item_thumbnail);
viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_text);
viewHolder.button = (Button) convertView.findViewById(R.id.list_item_btn);
convertView.setTag(viewHolder);
}
else {
mainViewHolder = (MainActovity.ViewHolder) convertView.getTag();
}
// Here, you need to set what values to show for this row - this
// is why your list is empty/blank
mainViewHolder.title.setText((String)getItem(position));
return convertView;
}

Android: delete from database using index from listview - Can't access array of id's that is created with the view but not the basis for the list

I have a simple list view where each item is a view that has a title, from an ArrayList of strings and button, so that each entry in the ArrayList creates a new list item.
I also have another ArrayList of corresponding primary keys, which I want to use to delete specific items from an SQLite database but which isn't used in the list view(I don't want to display the ID's, but the strings that poplulate the list might not necessarily be unique so I can't use them to delete).
I have a onClick listener and method in the getView method for the list view, so that when someone clicks the delete button, I know the position in the list that the button was pressed in, so hopefully, I can then call a delete method on the database using id[position], however, I think due to the list view itself being created after the activity it's inside of, it can't resolve the id array, so I can't call delete.
public class TodayListActivity extends AppCompatActivity {
private ArrayList<String> names = new ArrayList<>();
FoodDB Db = null;
int deleteId;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todaylist);
ListView lv = (ListView) findViewById(R.id.today_meal_list);
Bundle a = this.getIntent().getExtras();
String[] id = a.getStringArray("idArray"); //used to delete
String[] mealNames = a.getStringArray("mealNamesArray"); //displayed
Collections.addAll(names, mealNames);
//call the list adapter to create views based off the array list 'names'
lv.setAdapter(new MyListAdapter(this, R.layout.list_item, names));
}
protected class MyListAdapter extends ArrayAdapter<String> {
private int layout;
private MyListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder viewholder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
viewholder = new viewHolder();
viewholder.title = (TextView) convertView.findViewById(R.id.report_meal_name);
viewholder.delButton = (Button) convertView.findViewById(R.id.button_delete_meal);
viewholder.delButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer)v.getTag();
//int deleteId derived from id[position]
deleteId = Integer.parseInt(id[position]);
idToDelete(deleteId);
//update the list view to exclude the deleted item
names.remove(position);
notifyDataSetChanged();
}
});
convertView.setTag(viewholder);
} else {
viewholder = (viewHolder) convertView.getTag();
}
//set string value for title
viewholder.title.setText(getItem(position));
viewholder.delButton.setTag(position);
return convertView;
}
}
public class viewHolder {
TextView title;
TextView delButton;
}
//delete from database
public void idToDelete(int DeleteId){
Db.deleteFoods(deleteId);
}
}
Any suggestions as to how or where to get either the position index out of the list view (to the activity, where the id array is) or get access to the id array inside the listview would be appreciated!
You can pass the id array to the MyListAdapter adapter, by changing this class' constructor to accept it as a parameter. Also, you are already passing the names list as a parameter, you should keep a reference to it so you can access it when the button is pressed.
Here is an example:
protected class MyListAdapter extends ArrayAdapter<String> {
private int layout;
private List<String> names;
private String[] ids;
private MyListAdapter(Context context, int resource, List<String> names, String[] ids) {
super(context, resource, names);
layout = resource;
this.names = names;
this.ids = ids;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
...
viewholder.delButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int deleteId = Integer.parseInt(ids[position]);// the "position" variable needs to be set to "final" in order to access it in here.
idToDelete(deleteId);
names.remove(position);
notifyDataSetChanged();
}
});
....
}
}
and here is how you can create an instance of this adapter:
lv.setAdapter(new MyListAdapter(this, R.layout.list_item, names, id));

Load Multiple Images in ListView

I was following a NewBoston Tutorial (https://www.youtube.com/watch?v=nOdSARCVYic&list=PL6gx4Cwl9DGBsvRxJJOzG4r4k_zLKrnxl&index=48)
He showed how to put an image into a list but he never showed how to assign a different image to every piece of text.
Here is my MainActivity.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] Jobsites = {"River Park Place", "Mayfair", "Jameson House"};
ListAdapter jobsiteAdapter = new CustomAdapter(this, Jobsites);
ListView jobsiteListView = (ListView) findViewById(R.id.jobsiteListView);
jobsiteListView.setAdapter(jobsiteAdapter);
jobsiteListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String jobsite = String.valueOf(parent.getItemAtPosition(position));
//Toast.makeText(MainActivity.this, jobsite, Toast.LENGTH_LONG).show();
if (jobsite == "River Park Place"){
//Perform segue to the proper view where employess can sign in
//******************************************
System.out.println("*****************");
System.out.println("Attempting to segue");
System.out.println("*****************");
//******************************************
}else{
System.out.println("*****************");
System.out.println("These jobsites aren't avaliable yet!");
System.out.println("*****************");
Toast.makeText(MainActivity.this, "**These Sites aren't avaliable yet!**", Toast.LENGTH_LONG).show();
}
}
}
);
}
}
During the video we made a custom View that handles the images. Here is the code.
class CustomAdapter extends ArrayAdapter<String> {
public CustomAdapter(Context context, String[] jobsites) {
super(context,R.layout.custom_row ,jobsites);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater jobsiteInflater = LayoutInflater.from(getContext());
View customView = jobsiteInflater.inflate(R.layout.custom_row, parent, false);
String singleJobsiteItem = getItem(position);
ImageView josbiteImage = (ImageView) customView.findViewById(R.id.josbiteImage);
josbiteImage.setImageResource(R.drawable.riverparkplace);
return customView;
}
}
I have two other images that I want to add in for the bottom two items of text in the list. Right now it is just loading the SAME picture over and over again for all three rows in the list.
Let me guide you through this step by step. Before we continue, you need to understand that ArrayAdapter of your ListView populates each row with the data you specify to it. In other words, You would like to pass the image to the adapter just like you did with the Jobsites String array.
Define a simple wrapper object that contains your String (Jobsites) and the image you would like to assign to it.
public class SimpleObject {
private String jobSite;
private int imageID; // your R.drawable.image
public SimpleObject(String jobSite, int imageID) {
this.jobSite = jobSite;
this.imageID = imageID;
}
public String getJobSite() {
return jobSite;
}
public int getImageID() {
return imageID;
}
}
Initialise your SimpleObject array to be used by the adapter. In your onCreate() of the main activity, do the following:
ArrayList<SimpleObject> objectList = new ArrayList<>();
objectList.add(new SimpleObject("River Park Place", R.drawable.image1);
objectList.add(new SimpleObject("Mayfair", R.drawable.image2);
// the list goes on....
Now, change your CustomAdapter to hold the SimpleObject instead of String:
class CustomAdapter extends ArrayAdapter<SimpleObject> {
public CustomAdapter(Context context, ArrayList<SimpleObject> objectList) {
super(context,R.layout.custom_row ,objectList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater jobsiteInflater = LayoutInflater.from(getContext());
View customView = jobsiteInflater.inflate(R.layout.custom_row, parent, false);
// Get the SimpleObject
SimpleObject item = (SimpleObject) getItem(position);
String singleJobsiteItem = item.getJobSite(); // get the String
ImageView josbiteImage = (ImageView) customView.findViewById(R.id.josbiteImage);
josbiteImage.setImageResource(item.getImageID()); // get the image ID and assign it to jobsiteImage :)
return customView;
}
}
Now make sure you initialise the adapter in your main activity with the new SimpleObject list:
ListAdapter jobsiteAdapter = new CustomAdapter(this, objectList);
You need to implement baseadapter because of the images

Having problems while trying to populate a todo listview using a custom adaptor?

I want a user to input data through an editable text and I want to receive that data through a custom made listview, for that I am trying to use a custom adapter to add a textfield into my listview, through the tostring() method I have converted the data from the editable textview to a string and I am adding that string within my custom adapter to an Arraylist variable values and I’m trying to display that data through get(0) but either the Arraylist is not populating correctly or the data is not displaying properly because whenever I type something within my editable text and press the add button nothing happens, before this I added the string to an Array Adapter and the listview was populating normally, what am I doing wrong?
public class todoFragment extends ListFragment {
private EditText mToDoField;
private Button mAdd;
UsersAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setTitle(R.string.todo_title);
}
public class UsersAdapter extends ArrayAdapter<String> {
public Context context;
public ArrayList<String> values;
public UsersAdapter(Context context, ArrayList<String> values) {
super(context, 0, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = LayoutInflater.from(getContext()).inflate(R.layout.todo_list, parent, false);
TextView todoTextView = (TextView) convertView.findViewById(R.id.todo_TextView);
todoTextView.setText(values.get(0));
return convertView;
}
}
#TargetApi(9) // remember this for isEmpty()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_todo, container, false);
ArrayList<String> todoList = new ArrayList<String>();
mAdapter = new UsersAdapter(getActivity(), todoList);
ListView listViewToDo = (ListView) v.findViewById (android.R.id.list);
listViewToDo.setAdapter(mAdapter);
mToDoField = (EditText) v.findViewById(R.id.todo_editText);
mAdd = (Button)v.findViewById(R.id.add_button);
mAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String toDo = mToDoField.getText().toString().trim();
if (toDo.isEmpty()){
return;
}
mAdapter.values.add(toDo);
mToDoField.setText("");
}
});
return v;
}
}
Firstly, you should not be doing
todoTextView.setText(values.get(0));
Because this will always return the first element of the values list. You should do
todoTextView.setText(values.get(position));
Secondly,
mAdapter.values.add(toDo);
is not really right. It will work, but its not the best practise. Try using something like
mAdapter.add(toDo);
or
values.add(toDo);
Now once you've added the data to the list, you need to notify the adapter that the data set has been changed. This is done by
mAdapter.notifyDataSetChanged();
When you manually update the data don't forget to call:
mAdapter.notifyDataSetChanged();
Instead of mAdapter.values.add(toDo); UsemAdapter.add(toDo);
Look at the Add Method Of ArrayAdpter Class, it Itself use notifyDataSetChanged() so need to write any extra line of code:
public void add(T object) {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.add(object);
} else {
mObjects.add(object);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}

NullPointerException on populating data in BaseAdapter

I'm trying to populate a listview with data passed into the activity via a the intent that created it. The println statement you see confirms that the data is passed in correctly (i.e. the expected content is printed, meaning that the ArrayList referenced in the adapter is properly initialized). However, I keep getting a NullPointerException on the line
content.setText(Html.fromHtml(cmts.get(position).content));
There must be something wrong in the adapter - maybe in the getItem(), or perhaps my calls to cmts.get(position) isn't doing what I think it is, but at this point I can't figure it out.
public class CommentsView extends Activity {
ArrayList<Comment> cmts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments_view);
cmts = (ArrayList<Comment>) getIntent().getExtras().getSerializable("clist");
for (Comment c : cmts) {
System.out.println("CMTinCV: " + c.content);
}
ListView lv = (ListView)findViewById(R.id.commentsList);
CommentAdapter ca = new CommentAdapter();
lv.setAdapter(ca);
}
class CommentAdapter extends BaseAdapter {
public CommentAdapter(){
}
#Override
public int getCount() {
return cmts.size()-1;
}
#Override
public Object getItem(int position) {
return cmts.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.commentbox, null);
TextView content = (TextView)findViewById(R.id.commentText);
TextView author = (TextView)findViewById(R.id.commentAuthor);
TextView date = (TextView)findViewById(R.id.commentDate);
content.setText(Html.fromHtml(cmts.get(position).content));
author.setText(cmts.get(position).author.name);
date.setText(cmts.get(position).date);
}
return convertView;
}
}
}
You need to access the textview's in your getview method as below:
convertView.findViewById(R.id.commentText); access it like this.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.commentbox, null);
TextView content = (TextView)convertView.findViewById(R.id.commentText);
TextView author = (TextView)convertView.findViewById(R.id.commentAuthor);
TextView date = (TextView)convertView.findViewById(R.id.commentDate);
content.setText(Html.fromHtml(cmts.get(position).content));
author.setText(cmts.get(position).author.name);
date.setText(cmts.get(position).date);
}
return convertView;
}
Change your Adapter's constructor to this (if it's not an inner class for your activity) :
ArrayList<Comment> cmts;
public CommentAdapter(ArrayList<Comment> mComments){
this.cmts = mComments;
}
and these lines :
TextView content = (TextView)findViewById(R.id.commentText);
TextView author = (TextView)findViewById(R.id.commentAuthor);
TextView date = (TextView)findViewById(R.id.commentDate);
should be like :
TextView content = (TextView) convertView.findViewById(R.id.commentText);
TextView author = (TextView) convertView.findViewById(R.id.commentAuthor);
TextView date = (TextView) convertView.findViewById(R.id.commentDate);
Check if the variable is null or not first:
if(cmts.get(position) != null) {
content.setText(Html.fromHtml(cmts.get(position).content));
author.setText(cmts.get(position).author.name);
date.setText(cmts.get(position).date);
}
To create the adapter like this
CommentAdapter ca = new CommentAdapter(cmts);
And CommentAdapter class to create constructor like this
public CommentAdapter(ArrayList<Comment> cmts){
this.cmts = cmts;
}
And create local variable in CommentAdapter class
private ArrayList<Comment> cmts;

Categories