Load Multiple Images in ListView - java

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

Related

Listview show only last item over and over

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.

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));

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();
}

Updating ListView On Custom ArrayAdapter

I apologize if this is similar to other threads, but I have yet to find a good solution on how to update the ListView in my custom ArrayAdapter.
I'm extending FragmentActivity in order to create a custom Dialog popup for adding / updating new List entries (which works fine), but I can't seem to get the ListView in ServerActivityArrayAdapter to update after a change is made.
Obviously, adapter.notifyDataSetChanged(); in the ServersActivity class isn't enough, but I'm stumped as to how to get my ListView to update after the Save button is clicked in the ServerDialog popup. Any help would be greatly appreciated!
public class ServersActivity extends FragmentActivity {
private List<Server> server;
private ListView lv;
private ServerActivityArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server_list);
server = getServers();
lv = (ListView) findViewById(android.R.id.list);
adapter = new ServerActivityArrayAdapter(this, R.layout.server_list_item, server);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showServerDialog(position);
}
});
}
...
private void showServerDialog(int position) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
ServerDialog serverDialog = new ServerDialog(position);
ServerDialog.newInstance();
serverDialog.show(fragmentManager, "server_dialog");
}
ServerDialog class for adding new List entries
public class ServerDialog extends DialogFragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.settings_fragment, container);
context = getActivity().getApplicationContext();
dbh = new DbHandler(context);
etName = (EditText) view.findViewById(R.id.etName);
etAddress = (EditText) view.findViewById(R.id.etAddress);
etPort = (EditText) view.findViewById(R.id.etPort);
swtchNumDoors = (Switch) view.findViewById(R.id.swtchNumDoors);
Button btnSave = (Button) view.findViewById(R.id.btnSave);
loadData();
String title = (!newServer) ? "Edit Server" : "Add A New Server " + ID;
getDialog().setTitle(title);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
server[ID] = String.valueOf(ID);
server[SERVER_NAME] = etName.getText().toString();
server[ADDRESS] = etAddress.getText().toString();
server[PORT] = etPort.getText().toString();
if (server[ADDRESS].isEmpty() || server[PORT].isEmpty()) {
Toast.makeText(context, "Invalid Entry", Toast.LENGTH_LONG).show();
} else {
saveData();
// TODO - notify ServersActivity of change
}
}
});
return view;
}
public class ServerActivityArrayAdapter extends ArrayAdapter<Server> {
private int layout;
private String[][] values;
private int defServer;
private static LayoutInflater inflater;
ServerActivityArrayAdapter class for displaying ListView
public ServerActivityArrayAdapter(Context context, int layout, List<Server> servers) {
super(context, layout, servers);
this.layout = layout;
int i = 0;
values = new String[servers.size()][5];
for (Server server : servers) {
values[i][0] = Integer.toString(server.id);
values[i][1] = server.name;
values[i][2] = server.address;
values[i][3] = Integer.toString(server.port);
values[i][4] = Integer.toString(server.num_doors);
defServer = (server.default_server) ? i : 0;
i++;
}
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private static class ViewHolder {
private TextView tvServerName;
private CheckBox cbDefault;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
try {
if(v == null) {
v = inflater.inflate(layout, parent, false);
holder = new ViewHolder();
holder.tvServerName = (TextView) v.findViewById(R.id.tvServerName);
holder.cbDefault = (CheckBox) v.findViewById(R.id.cbDefault);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.tvServerName.setText(values[position][1]);
holder.cbDefault.setChecked(defServer==position);
} catch (Exception e){
System.out.println(e);
}
return v;
}
You could use an interface and have a method in it maybe named updateListView().
Implement this interface in your FragmentActivity. In the implemented method, add code to update the listView.
And in the button code of your dialog, call ((Interfacename) getActivity).updateListView()
Your problem is in the implementation of the adapter. You are instantiating the ArrayAdapter with a List<Server> object (The super call) but then creating your own two dimensional array values to contain the data. You use the values array for the getView() method yet make no mention or show through code how you actually modify that data to update the adapter.
You should be calling back into the adapter to update it. EG, calling add(), remove(), etc. You only mention updating the DB which has nothing to do with updating your adapter. It's not linked in anyway to the DB. Even if you were to call into the previously mentioned mutate methods on the adapter, they wouldn't work unless you specifically override them. The default ArrayAdapter implementation will modify the List<Server> data and not the values two-dim array you created.
But if you find yourself override those mutate methods to support your values two-dim array...there's no point in subclassing the ArrayAdapter. Part of the point of the ArrayAdapter is handling all the data management for you. In such a situation you should be instead subclassing BaseAdapter.

Refresh ListView Items upon button triggered

I was having some problem when trying to refresh the items in list view after the button was triggered. Here is how I populate the listview onCreate:
public class EventChat extends Fragment {
Context context;
View eventChat;
String userID, eventID;
private ListView listview;
public ArrayList<EventComment> _commentlist = new ArrayList<EventComment>();
TextView txtDisplayCommentBy, txtDisplayDateTime, txtDisplayCommentDesc,
txtEventChat;
Button btnChatSubmit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
eventChat = inflater.inflate(R.layout.event_chat, container, false);
context = getActivity();
listview = (ListView) eventChat.findViewById(R.id.listview);
txtEventChat = (TextView) eventChat.findViewById(R.id.txtEventChat);
btnChatSubmit = (Button) eventChat.findViewById(R.id.btnChatSubmit);
btnChatSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onSubmitChatClicked();
}
});
Intent i = getActivity().getIntent();
_commentlist = (ArrayList<EventComment>) i
.getSerializableExtra("eventCommentObj");
Event eventModel = (Event) i.getSerializableExtra("eventObj");
userID = "Gab";
eventID = eventModel.getEventID();
listview.setAdapter(new ListAdapter(getActivity()));
return eventChat;
}
private class ListAdapter extends BaseAdapter {
LayoutInflater inflater;
ViewHolder viewHolder;
public ListAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public int getCount() {
return _commentlist.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.eventchat_listview_row,
null);
viewHolder = new ViewHolder();
viewHolder.txt_dcommentBy = (TextView) convertView
.findViewById(R.id.txtDisplayCommentBy);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_dcommentBy.setText(_commentlist.get(position)
.getCommentBy().trim());
return convertView;
}
}
private class ViewHolder {
TextView txt_dcommentBy;
TextView txt_ddateTime;
TextView txt_dcommentDesc;
}
}
When my button was triggered and insert a new record into database, at the same time, I wanted the list view items to be refreshed:
public void onSubmitChatClicked() {
EventComment commentModel = new EventComment();
String currentDate = EventDateTime.getCurrentDate();
String currentTime = EventDateTime.getCurrentTime();
String commentDesc = String.valueOf(txtEventChat.getText());
commentModel.setCommentBy(userID);
commentModel.setEventID(eventID);
commentModel.setCommentDate(currentDate);
commentModel.setCommentTime(currentTime);
commentModel.setCommentDesc(commentDesc);
new CreateCommentAsyncTask(context).execute(commentModel);
txtEventChat.setText("");
}
However, it does not refresh. Any ideas?
Thanks in advance.
Well this looks pretty straightforward.
First make your adapter a class member, so you can access it later:
private ListAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
mAdapter = new ListAdapter(getActivity();
listview.setAdapter(mAdapter);
...
}
Then, when you submit the item, also add it to your ArrayList and update your adapter:
public void onSubmitChatClicked() {
EventComment commentModel = new EventComment();
String currentDate = EventDateTime.getCurrentDate();
String currentTime = EventDateTime.getCurrentTime();
String commentDesc = String.valueOf(txtEventChat.getText());
commentModel.setCommentBy(userID);
commentModel.setEventID(eventID);
commentModel.setCommentDate(currentDate);
commentModel.setCommentTime(currentTime);
commentModel.setCommentDesc(commentDesc);
// Add the new element to your DB
new CreateCommentAsyncTask(context).execute(commentModel);
// Add the new element to your current ArrayList
_commentlist.add(commentModel)
// Update theListView, by updating the adapter
mAdapter.notifyDataSetChanged();
txtEventChat.setText("");
}
EDIT:
Little more explanation:
When your fragment is created you are passed an array of EventComment items. I guess these are the elements from your DB. When you update the database, however, your ArrayList won't get updated, unless you reload the whole fragment. That's why you add the item to the DB, and to the list manually, and with notifyDataSetChanged, you force your adapter to update the ListView.
You cant do listview.setAdapter(new ListAdapter(getActivity())); to achieve this. You should create an instance of adapter and call adapter.add + adapter.notifyDataSetChanged
This is a very good tutorial :
http://www.vogella.com/tutorials/AndroidListView/article.html
http://www.javacodegeeks.com/2013/09/android-listview-with-adapter-example.html

Categories