ListView displays item after 2nd item has been created - android

So I'm having a weird order of events in my code. It'll probably be something minor that I haven't seen yet. A have ListView that and is pulling the string from an EditText after button click.
The EditText lives in a dialog that's being pulled back to the main Activity by an interface
What happens now, is when I type something in the EditText field say "a", nothing shows up. But when I go to add another, "b", "a" shows up. and so forth. So one has to be created in order for the previous to show up.
Here's my what I have.
public class NewActivity extends FragmentActivity implements AddSiteDialog.AddSiteDialogListener {
ListView mSiteListView;
ArrayList<String> siteList = new ArrayList<String>();
CustomAdapter arrayAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_site);
mSiteListView = (ListView) findViewById(R.id.siteAddList);
arrayAdapter = new CustomAdapter();
mSiteListView.setAdapter(arrayAdapter);
Button b = (Button) findViewById(R.id.addSiteButton);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
}
});
}
public void showDialog() {
FragmentManager fm = getSupportFragmentManager();
AddSiteDialog addSiteDialog = new AddSiteDialog();
addSiteDialog.show(fm, "main");
}
public void onSignIn(String inputText) {
siteList.add(inputText);
}
class CustomAdapter extends ArrayAdapter<String> {
CustomAdapter() {
super(NewActivity.this, R.layout.add_site, siteList);
}
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
if (row == null){
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.list_row, parent, false);
}
((TextView) row.findViewById(R.id.textViewId)).setText(siteList.get(position));
return (row);
}
}
}
Can anyone spot where this is happening?

Simple.
call arrayAdapter.notifyDataSetChanged() in
public void onSignIn(String inputText) {
siteList.add(inputText);
//add that here
}

If the data which is backed by your adapter changes, you need to call notifyDataSetChanged() on your adapter to instruct the ListView to update itself.
I don't see anything like that in your code.
Just to add:
Your adapter implementation is sub-optimal - although in this case it doesn't really matter.
You should create a ViewHolder and store it as your View's tag, so that you can retrieve it if convertView is given. The ViewHolder should keep references to all sub-views of your view (TextView, ImageView, whatever you need to update). This would avoid the repeated call to findViewById() - which is slow.

Related

Listview not updating after arraylist is updated?

I've seen many other posts in this context, but none helped. Problem is when i click on the addField button, the listview inside dialog adds new view just once. But at other clicks it doesn't get updated though The adapter works correctly (I mean the getView is called and also the arrayList in the adapter is changed in size).
I've used notifyDataSetChanged() in the adapter class. No result! I used an instance of adpater class in activity and called myAdapter.notifyDataSetChanged(). No result!
here is my code:
public class MainActivity extends Activity {
ListView lvfid;
FieldAdapter fAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some code
showFid();
}
private void showFiD(){
final ArrayList <HashMap<String,String>> al = new ArrayList<HashMap<String,String>>();
final Dialog dialog = new Dialog(MainActivity.this , R.style.DialogTheme);
dialog.setContentView(R.layout.field_dialog);
dialog.setCancelable(true);
dialog.show();
Button addField = (Button) dialog.findViewById(R.id.btnfidField);
lvfid = (ListView) dialog.findViewById(R.id.lvfid);
//Another plan i have tested, but no result:
//fAdapter = new FieldAdapter(dialog.getContext(),al);
//lvfid.setAdapter(fAdapter);
addField.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
HashMap<String,String> h = new HashMap<String,String>();
h.put("name", "");
h.put("value", "");
al.add(h);
lvfid.setAdapter(new FieldAdapter(dialog.getContext(), al));
//fAdapter.notifyDataSetChanged();
}
});
}
public class FieldAdapter extends BaseAdapter{
private ArrayList <HashMap <String,String>> arrayList;
private LayoutInflater inflater;
public FieldAdapter(Context context, ArrayList<HashMap <String,String>> arrayList) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
View view = null;
if (convertView == null)
view = inflater.inflate(R.layout.field_inflater, null);
else
view = convertView;
Holder holder = new Holder();
holder.edName = (EditText) view.findViewById(R.id.edfidName);
holder.edValue = (EditText) view.findViewById(R.id.edfidValue);
//holder.edName.setText(arrayList.get(position).get("name"));
//holder.edValue.setText(arrayList.get(position).get("value"));
return view;
}
private class Holder {
private EditText edName;
private EditText edValue;
}
}
}
UPDATE:
I'm sorry i took everybody's time. The stupid problem was that my listview was inside a scrollview where it must not be! I hope this helps others who have the same issue!
Use the notifyDataSetChanged() every time the list is updated.
I had the same problem. I was facing with this problem when I wanted to update the listView after onDateChanged(). I resolved it with an extra ArrayList variable and an extra custom adapter in your case FieldAdapter variable.
Update your listView with a refresh adapter and array list variables after any operations. For example after button clicks.
1. Define a counter.
2. Check when the button is clicked, increase counter by one
3. Every time check the counter, if counter is greater than 1 it means the button is clicked more than once so update the list view with new variables (arrayList, FeildAdapter)
I recommend you to define the variables as a private class fields and name them such as refreshedArrayList and refreshedAdapter
Option
Try to use the ArrayAdapter. And don't create a new adapter every
time you click on the button.
only call the add(T o) function from the ArrayAdapter.
Other Option:
add a add function to your FieldAdapter in the add field adapter add the object to your arraylist and call notifiyDataSetChanged(the adapter has aslo one and the adapter notifies all his observers)
also don't create a new adapter every time you click the button.
public class MainActivity extends Activity {
ListView lvfid;
FieldAdapter fAdapter;
ArrayList <HashMap<String,String>> al ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some code
al = new ArrayList<HashMap<String,String>>();
lvfid.setAdapter(new FieldAdapter(MainActivity.this , al));
showFid();
}
private void showFiD(){
final Dialog dialog = new Dialog(MainActivity.this , R.style.DialogTheme);
dialog.setContentView(R.layout.field_dialog);
dialog.setCancelable(true);
dialog.show();
Button addField = (Button) dialog.findViewById(R.id.btnfidField);
lvfid = (ListView) dialog.findViewById(R.id.lvfid);
//Another plan i have tested, but no result:
//fAdapter = new FieldAdapter(dialog.getContext(),al);
//lvfid.setAdapter(fAdapter);
addField.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
HashMap<String,String> h = new HashMap<String,String>();
h.put("name", "");
h.put("value", "");
al.add(h);
fAdapter.notifyDataSetChanged();
}
});
}
I'm sorry i took everybody's time! The stupid problem was just my listview was inside a scrollview where it must not be! after getting the listview out of scrollview the problem got solved.

ListView creates one more item than needed

I have a ListView which is populated in my MainActivity, but when i want to find the selected item, all of the items appear to have the same position.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_teams);
ListView mainListView;
// Find the ListView in the UI.
mainListView = (ListView) findViewById( R.id.listView );
String values = "Team A vs Team B=Team C vs Team D";
//Matches are send in one long string, and are separated by the = sign.
//This splits the string up and puts it into an array.
String[] array = values.split("=", -1);
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.addAll( Arrays.asList(array) );
ArrayAdapter listAdapter;
// Create ArrayAdapter using the planet list.
listAdapter = new ArrayAdapter<String>(this, R.layout.list_view_style, arraylist);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter(listAdapter);
}
This makes a list like this:
Team A vs Team B [checkbox]
Team C vs Team D [checkbox]
I have a button and when it is clicked it runs this method:
public void matchStart(View view){
String selectedMatch = String.valueOf(((ListView) findViewById( R.id.listView )).getSelectedItemPosition());
Toast.makeText(SelectTeams.this, selectedMatch, Toast.LENGTH_SHORT).show();
}
However whenever i click the button, the toast displays the same value no matter which item in the listview is selected. Why is this?
You should use the adapters getView method, something like this:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.some_layout, parent,
false);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//here get what you need by the position
}
});
}
}

custom adapter do not refresh the listview for onclicklistener in android

I delete database entry using onclicklistener but it is not refreshing the listview. how can i refresh this listview?
This is main class for listview:
public class AFragment extends Fragment implements OnItemClickListener {
protected static final String file_name ="user";
ListView list;
Database entry;
View v;
String values[];
MySimpleArrayAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
SharedPreferences settings = getActivity().getSharedPreferences(file_name, 0);
String name = settings.getString("name", null);
entry = new Database(getActivity());
entry.open();
values=entry.planlist(name);
entry.close();
if(values.length>0){
v = inflater.inflate(R.layout.activity_afragment, container,false);
adapter = new MySimpleArrayAdapter(getActivity(), values);
list=(ListView)v.findViewById(R.id.list);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
list.setOnItemClickListener(this);
}else{
v = inflater.inflate(R.layout.activity_my_tabs_listener, container,false);
}
// Toast.makeText(getActivity(),String.valueOf(values.length), Toast.LENGTH_LONG).show();
return v;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity(),Details.class);
i.putExtra("sub", values[arg2]);
startActivity(i);
Toast.makeText(getActivity(), "clicked", Toast.LENGTH_SHORT).show();
}
}
Here i use onclicklistener to delete data from database but it is not refreshing:
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public Business aFragment = new Business();
int mypos =0;
ViewHolder holder;
View row;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context,R.layout.activity_my_simple_array_adapter, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
mypos = position;
row = convertView;
holder = new ViewHolder();
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(R.layout.activity_my_simple_array_adapter, parent, false);
TextView textView = (TextView) row.findViewById(R.id.text);
Button btn = (Button) row.findViewById(R.id.button1);
holder.tv = textView;
holder.btn = btn;
row.setTag(holder);
}else{
holder = (ViewHolder)row.getTag();
}
holder.tv.setText(values[position]);
final int id = position;
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Database entry = new Database(context);
entry.open();
entry.delete(values[id]);
entry.close();
// Toast.makeText(getContext(), String.valueOf(id), Toast.LENGTH_LONG).show();
}
});
return row;
}
static class ViewHolder{
TextView tv;
Button btn;
}
}
as anil said, you should put notifyDataSetChanged(); inside the onClickListener
this basically tells the adapter to render the list again and will call getView() again for every visible item in the list, if your code crashes, you should check two things:
first - debug the program and check that the new data fits what you want, in your case, check that the entry was deleted properly.
second - debug the getView method, step through each call and see what gives you the crash.
in your case the problem is that you are only updating the database, but in fact your listview data is taken from the values[] array which is not updated after you delete the database entry, you should create a function for updating it.
Put adapter.notifyDataSetChanged(); on click of ListView
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Database entry = new Database(context);
entry.open();
entry.delete(values[id]);
entry.close();
adapter.notifyDataSetChanged();
// Toast.makeText(getContext(), String.valueOf(id), Toast.LENGTH_LONG).show();
}
If you do lots of adding and deleting to the list I think you should do the things below.
You should use ArrayList<String> instead of simple String[] so that you can easily delete. Database deletion do not effect the list directly unless you use Loaders
After you delete and item from the list, you should call notifyDataSetChanged() to the adapter. If you do not call this method, the list wont be updated.
adapter.notifyDataSetChanged();
you are removing it from the database but you are not removing it from the dataset that fills up your ListView. The simplest thing you can do is to change values from array to ArrayList, and since you are using an ArrayAdapter, you can call remove(int position). You need a List<T> of objects otherwise remove will throws an exception.
You can do one thing.
Firstly create a method called myAdapter().
In this put your creation of adapter code,so you can create new adapter for loading new data by simply calling myAdapter() method.
Whenever there should be modification in your ListView just called the following code,
listview.invalidate();
Then simply call the myAdapter().
That's it.Hope this is useful to you..:)

ListView (button not running)

Practicing on the ListView, I thought of adding buttons as well to it, rather than showing only content. But in my implementation, the button does not do anything at all.
Plus I was confused whether I could get the position of the button clicked. For now I am just sending the toSend declared inside the OnItemClick in an intent.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
final int toSend = position;
TextView refId = (TextView)view.findViewById(R.id.list_id);
TextView refName = (TextView)view.findViewById(R.id.list_name);
TextView refAdd = (TextView)view.findViewById(R.id.list_address);
Button edit = (Button)view.findViewById(R.id.edit);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(ListActivity.this, EditLayout.class);
i.putExtra("position", toSend);
startActivity(i);
}
});
String sd_id = refId.getText().toString();
String sd_name = refName.getText().toString();
String sd_add = refAdd.getText().toString();
buildAlert(sd_id, sd_name, sd_add);
}
});
You're pretty close. The "inside" setOnClickListener needs to happen when you create the list row view (the view containing id, name, address, edit).
You can do that during getView(). But where to send the clicks? Instead of creating a new onClickListener, use "this" (your activity). Put an onClick() handler in the activity.
Then, when you get a click, the onClick method will execute. Next problem: how do you know which row clicked? The easiest way that comes to mind is to give the button a different id for e ach row - use the row index (you might need to start at 1 rather than 0 - be warned).
Finally, given the row id, it's easy to start your "nested" activity.
Hope this helps.
(added later)
I do it like this; you'll need to define a layout for your row view:
class MyActivity extends Activity implements View.OnClickListener
{
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.my_page);
ListView list = (ListView)findViewById (android.R.id.list);
MyArrayAdapter adapter = new MyArrayAdapter (this, <your array of data>);
list.setAdapter (adapter);
}
#Override
public void onClick(View v)
{
int buttonId = v.getId();
if (buttonId is within range)
... do what you need to do with the click ...
}
private class MyArrayAdapter extends ArrayAdapter<MyData>
{
private Activity act;
//-----------------------------------------------------------------------------
public MyArrayAdapter (Activity act, MyData array)
{
super (act, R.layout.list_row, array);
this.act = act;
}
//-----------------------------------------------------------------------------
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
ViewGroup rowView = (ViewGroup)convertView;
if (rowView == null)
{
LayoutInflater inflater = act.getLayoutInflater();
rowView = (ViewGroup) inflater.inflate (R.layout.list_row,
parent, false);
}
Button button = (Button)rowView.findViewById (R.id.is_member);
button.setId (position+1); // add one to avoid 0 as an id.
button.setOnClickListener (act);
// set field values here -- not shown
return rowView;
}
}
}

Android: How to make a button list with text info from database

I'm doing a simple "quest" app. Each quest consist of a checklist of things to do. I want to show the list of quests available with buttons showing the title of each quest.
I have each quest and its specs in a db. Following some tutorials like this one they use an ArrayAdapter to show the list, but it requires a "textview resource id" in the layout. I don't know how to pass the title of each quest (which I retrieve from the db) to the layout and put it on the button, since I never use text views.
For clarity, here is the code of the activity where I retrieve the data from de DB.
public class InProgress extends ListActivity {
private questspecdao datasource;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new questspecdao(this);
datasource.open();
List<questspec> values = datasource.getAllQuests();
ArrayAdapter<questspec> adapter = new ArrayAdapter<questspec>(this,
R.layout.questrow, values);
setListAdapter(adapter);
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Thanks in advance!
You're making the wrong adaptation of the ArrayAdapter.
According with Android's official documentation, an ArrayAdapter, "By default this class expects that the provided resource id references a single TextView"
That means it only supports a TextView so you have to implement it like:
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array /** Your data String[] goes here. */);
/** Sets adapter to your declared ListView. */
youtListView.setAdapter(arrayAdapter);
If you want a customized list item then you must create your own adapter:
public class MyArrayAdapter extends ArrayAdapter<String> {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
/** Inflate a xml layout to the View. */
View itemView = inflater.inflate(R.layout.rowlayout, parent, false);
/**Declare all of your items at the previous defined rowlayout xml file . */
TextView textView = (TextView) itemView .findViewById(R.id.textView);
ImageView imageView = (ImageView) itemView .findViewById(R.id.icon);
/** Set some values to the declared item views. */
textView.setText(values[position]);
if (values[position].contains("XXXXXXX")) {
imageView.setImageResource(R.drawable.x);
} else {
imageView.setImageResource(R.drawable.y);
}
return itemView;
}
}
Let me know if that helped you :)

Categories

Resources