Android: positioning items in ListView menu in java? - java

I am really new into Android development, so I am sorry if this question may sound funny to some of you.
I need to center the items of my ListView Menu just for the sake of aestheticism, but I really don't know how since the code is written only in java without the use of XML.
package com.example.mysqltest;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Menu extends ListActivity {
String classes[] = {"ProductList", "example1", "example2", "example3", "example4", "example5"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String local = classes[position];
try {
Class ourClass = Class.forName("com.example.mysqltest." + local);
Intent ourIntent = new Intent(Menu.this, ourClass);
startActivity(ourIntent);
} catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}

You can change the layout you are passing to your adapter here:
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes));
This piece is the layout of the row:
android.R.layout.simple_list_item_1
Check this answer that explains what it is.

You need to create your own Adapter :
public class MyAdapter extends BaseAdapter{
private LayoutInflater inflater;
private List<String> data;
public MyAdapter(Context context, List<String> data){
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.data = data;
}
public int getSize(){
return data.getSize();
}
public Object getItem(int position){
return data.get(position);
}
public View getView(View convertView, int position, ViewGroup parent){
View v = convertView;
ViewHolder h;
if(v == null){
v = inflater.inflate(R.layout.my_adapter, false);
h = new ViewHolder();
t.tv = (TextView) v.findViewById(R.id.my_textview);
v.setTag();
}else{
h = (ViewHolder) v.getTag();
}
String s = (String) getItem(position);
h.tv.setText(s);
return v;
}
public class ViewHolder{
TextView tv;
}
}
I don't really remember by heart because of the autocompletion in Eclipse, but it should look like this.
Your my_adapter.xml is where you will place your TextView everywhere you want, you will be able to add more, like ImageViews and others TextViews.
And to call it it's simple :
MyAdapter adapter = new MyAdapter(context, myList);
listView.setAdapter(adapter);

It's not only written in Java, you have to supply an XML layout for the Adapter to inflate. In your case, you've got R.layout.simple_list_item_1. Where you set it here:
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes));
As you've not posted the content of R.layout.simple_list_item_1 - I have to assume that it's just a TextView that's contained within it. As such, you can quite easily align text with something like the following:
TextView textView =(TextView)findViewById(R.id.texviewid);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
Failing that, you could always set it within the XML of R.layout.simple_list_item_1 and not worry about it.
Hope this helps.

just write this code before setting adapter,here lv is your listview
lv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

Related

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

ListVIew in Fragment Very Laggy

I have a ViewPager with 3 fragments. The rightmost fragment has a ListView inside it. The problem is that on two weaker phones I tested this on, it works seemingly smooth and not laggy. However, when I test it on my Note 3, the transition from the middle fragment to this one is very laggy and over 300 frames are skipped according to the logcat. Also, if I lock the phone and then unlock it back onto the ListView it is very laggy to scroll or do anything, unless I swipe left twice to the leftmost fragment. This is my onCreateView, onAttach and onStart methods as well as the adapter below.
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_c,container,false);
mainalyout = (LinearLayout) view.findViewById(R.id.linear_layout_listview);
listView = (ListView) view.findViewById(R.id.followed_cities);
horizontal_scroll = (HorizontalScrollView) view.findViewById(R.id.horizontal_scroll_view);
swipe = (LinearLayout) view.findViewById(R.id.scroll_up);
layout = (LinearLayout) view.findViewById(R.id.scroll_view_layout);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = MyApp.getContext();
session = new SessionManager(context);
userString = session.getUserDetails();
username = userString.get("username");
viewPager = (ViewPager) activity.findViewById(R.id.pic_pager);
parent = (FragmentActivityTesting) activity;
username = userString.get("username");
queue = Volley.newRequestQueue(context);
followed_cities = session.getFollowedCities();
try {
citysearcher = (citysearcher) activity;
} catch(Exception e) {}
try {
slideshowready = (slideshowready) activity;
}catch (Exception e) {}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
swipeRefreshLayout.setOnRefreshListener(this);
if (followed_cities.contains("")) {
followed_cities.clear();
}
if (getActivity().getIntent().getStringExtra("launcher").equals("add")) {
get_followed(username);
}
if (followed_cities.isEmpty()) {
followed_cities.add(new CityShort("","NONE"));
ArrayAdapter<CityShort> adapter = new EmptyAdapter();
adapterr = adapter;
listView.setAdapter(adapterr);
}
else {
ArrayAdapter<CityShort> adapter = new MyListAdapter();
adapterr = adapter;
listView.setAdapter(adapterr);
}
My adapter :
private class MyListAdapter extends ArrayAdapter<CityShort> {
public MyListAdapter() {
super(getActivity(), R.layout.followed_item, followed_cities);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
itemView = convertView;
if (itemView == null) {
itemView = getActivity().getLayoutInflater().inflate(R.layout.followed_item, parent, false);
}
TextView city_name = (TextView) itemView.findViewById(R.id.followed_city_txt);
final String curr_city = followed_cities.get(position).getCityName();
city_name.setText(curr_city);
city_name.setTag(followed_cities.get(position).getCityId());
if (curr_city.length() > 15) {
city_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
}
listView.setOnTouchListener(swipeDetector);
return itemView;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
}
I saw you had 2 listviews (findViewById(R.id.followed_cities) and findViewById(R.id.horizontal_scroll_view)). The horizontal listview is not well-implemented for recycling items.
Consider a better official support solution with RecyclerView. It supports both vertical and horizontal and provides better performance (as least the number of frames skipped will be less than current listview).
Two things that I see:
1) You have several LinearLayouts. I'm not certain what your xml layout looks like, but if LinearLayouts are nested they can certainly reduce visual rendering time. RelativeLayouts are more efficient(though I do use LinearLayouts when I'm first writing the xml file, because it's a little less time consuming for me as a general setup, then to later go back and update to using RelativeLayout).
2) You're doing all of these calculations on your MainThread, which is also Android's GPU essentially. You might be interested in processing all of this on a separate thread, this will certainly reduce rendering time. Check out "extends AsyncTask" and "Intent Service".
Change these things and try if works..
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = getActivity().getLayoutInflater().inflate(R.layout.followed_item, parent, false);
city_name = (TextView) itemView.findViewById(R.id.followed_city_txt); //Make this class level variable
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Replace your adapter with this
package com.munk.gaanasync;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.view.LayoutInflater;
import java.util.zip.Inflater;
private class MyListAdapter extends ArrayAdapter<CityShort>
{
public MyListAdapter()
{
super(getActivity(), R.layout.followed_item, followed_cities);
mInflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
itemView = convertView;
if (itemView == null)
{
holder = new ViewHolder();
itemView = mInflater.inflate(R.layout.followed_item, parent, false);
holder.city_name = (TextView) itemView.findViewById(R.id.followed_city_txt);
itemView.setTag(holder);
}
else
{
holder = (Viewholder) itemView.getTag();
}
final String curr_city = followed_cities.get(position).getCityName();
holder.city_name.setText(curr_city);
holder.city_name.setTag(followed_cities.get(position).getCityId());
if (curr_city.length() > 15)
{
holder.city_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
}
listView.setOnTouchListener(swipeDetector);
return itemView;
}
public static class ViewHolder
{
public TextView city_name;
}
#Override
public int getViewTypeCount()
{
return getCount();
}
#Override
public int getItemViewType(int position)
{
return position;
}
private Inflater mInflater;
}

Android ListView with LinkedHashMap - scrambled list when scrolling

I've had trouble finding much documentation on using LinkedHashMap with a ListView for Android, but I was able to get the list to populate correctly with the below.
Unfortunately, when I scroll, the list is scrambled the same as it would be if I was using a regular HashMap. I'm not sure what I'm doing wrong.
MainActivity.java (only a portion):
public class MainActivity extends ListActivity {
private ListView dataList;
ArrayList<String> listItems=new ArrayList<String>();
ListViewAdapter adapter;
private ArrayList<LinkedHashMap<String, String>> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = (ListView)findViewById(android.R.id.list);
list=new ArrayList<LinkedHashMap<String,String>>();
adapter=new ListViewAdapter(this, list);
dataList.setAdapter(adapter);
addItems();
}
public void addItems() {
LinkedHashMap<String,String> row = new LinkedHashMap<String, String>();
row.put(KEY_COLUMN, key);
row.put(FIRST_COLUMN, dateTime);
row.put(SECOND_COLUMN, data1);
row.put(THIRD_COLUMN, data2);
row.put(FOURTH_COLUMN, data3);
list.add(row);
adapter.notifyDataSetChanged();
}
}
ListViewAdapter Class
public class ListViewAdapter extends BaseAdapter{
public ArrayList<LinkedHashMap<String, String>> list;
Activity activity;
TextView txtKey;
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
TextView txtFourth;
public ListViewAdapter(Activity activity,ArrayList<LinkedHashMap<String, String>> list){
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null){
LayoutInflater inflater = activity.getLayoutInflater();
convertView = inflater.inflate(R.layout.list_row_columns, null);
txtKey = (TextView) convertView.findViewById(R.id.row_key);
txtFirst = (TextView) convertView.findViewById(R.id.date_time);
txtSecond = (TextView) convertView.findViewById(R.id.data1);
txtThird = (TextView) convertView.findViewById(R.id.data2);
txtFourth = (TextView) convertView.findViewById(R.id.data3);
}
LinkedHashMap<String, String> map = list.get(position);
txtKey.setText(map.get(KEY_COLUMN));
txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
txtThird.setText(map.get(THIRD_COLUMN));
txtFourth.setText(map.get(FOURTH_COLUMN));
return convertView;
}
}
The simplest solution would be to use ArrayAdapter rather than rolling your own BaseAdapter subclass. But, assuming that you really want to extend BaseAdapter...
First, get rid of all of the widgets from the class declaration (e.g., TextView txtKey), moving them to be local variables inside of getView().
Then, populate those local variables whether or not you are inflating a new layout.
Other improvements:
Never use LayoutInflater.from() when you have an Activity. Call getLayoutInflater() on the Activity, so you get a LayoutInflater that knows about your themes and styles.
Use getItem(), instead of list.get(position), in getView(), so getView() and getItem() stay in sync.

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.

Categories