update the text of a listView row - java

I want my listView to be updated after clicking on a row (or any event, but let's focus on click).
I did something, but it updates more than one row (maybe it updates the first visible row and the one after the last visible...).
Here is the full code
Activity code
DatabaseHandler colisageBase;
ListView listView;
List<Site> sites;
String id_tournee;
SiteAdapter siteAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_site_choice);
Intent intent = getIntent();
id_tournee = intent.getStringExtra("idTourneeSelectionnee");
this.listView = findViewById(R.id.list_view_site);
this.colisageBase = new DatabaseHandler(this);
sites = colisageBase.selectAllSite(id_tournee);
siteAdapter = new SiteAdapter(SiteChoiceActivity.this, sites);
listView.setAdapter(siteAdapter);
colisageBase.closeDB();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Site selectedSite = sites.get(position);
selectedSite.setIsBarred(true);
sites.set(position, selectedSite);
siteAdapter.notifyDataSetChanged();
//goToOperationActivity(selectedSite.SiteOut());
}
});
Adapter code
public class SiteAdapter extends ArrayAdapter<Site> {
public SiteAdapter(Context context, List<Site> sites) {
super(context, 0, sites);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_site,parent, false);
}
SiteViewHolder viewHolder = (SiteViewHolder) convertView.getTag();
if(viewHolder == null){
viewHolder = new SiteViewHolder();
viewHolder.heure_supposee = convertView.findViewById(R.id.heure_supposee);
viewHolder.libelle_site = convertView.findViewById(R.id.libelle_site);
viewHolder.logo_telephone = convertView.findViewById(R.id.logo_phone);
convertView.setTag(viewHolder);
}
Site site = getItem(position);
viewHolder.heure_supposee.setText(site.getHeure_supposee());
viewHolder.libelle_site.setText(site.getLibelle_site());
viewHolder.logo_telephone.setVisibility(View.INVISIBLE);
if (site.getSur_appel().equals("O")) viewHolder.logo_telephone.setVisibility(View.VISIBLE);
if (site.isBarred()) viewHolder.libelle_site.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
return convertView;
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
private class SiteViewHolder{
public TextView heure_supposee;
public TextView libelle_site;
public ImageView logo_telephone;
}
}
Please suggest what's wrong with the code.

The answer was given in the comments by I_A_Mok, but i have to add more details:
In the case of a cell, when you do an action in an "if" condition , you usually have to do the opposite in an "else" condition.
In my case, after my condition where I strike through text, I had to add an else condition where I don't strike through text.
if (site.isBarred()){
viewHolder.libelle_site.setPaintFlags(viewHolder.libelle_site.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}else {
viewHolder.libelle_site.setPaintFlags(viewHolder.libelle_site.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
}

Related

switch state is not stable in listview when scrolling

I'am new to android and i use sample for my listview. because of that i can't change the code. i have one switch button in each item of my Listview. when i scroll the Listview switches change state randomly. how can i make switch state stable?
my listview class adapter:
public class MyCustomCursorAdapter extends CursorAdapter {
LIGHTS calling_activity;
private DatabaseHelper dbHelper;
public MyCustomCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
this.calling_activity = (LIGHTS) context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
return view;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.adapter,parent,false);
}
#Override
public void bindView(final View view, Context context, Cursor cursor) {
((TextView)view.findViewById(R.id.id)).setText(cursor.getString(cursor.getColumnIndex(dbHelper._ID)));
((TextView)view.findViewById(R.id.KEYCODE)).setText(cursor.getString(cursor.getColumnIndex(dbHelper.TITLE)));
((TextView)view.findViewById(R.id.NAME)).setText(cursor.getString(cursor.getColumnIndex(dbHelper.DESC)));
ImageView option = view.findViewById(R.id.itemoption);
Switch thisswitch = view.findViewById(R.id.onoff);
thisswitch.setTag(cursor.getString(cursor.getColumnIndex(dbHelper._ID)));
thisswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { calling_activity.myOnCheckedChangedHandler((String)buttonView.getTag(),isChecked);
}
});
option.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView itemID = (TextView) view.findViewById(R.id.id);
TextView itemTitle = (TextView) view.findViewById(R.id.KEYCODE);
TextView itemDesc = (TextView) view.findViewById(R.id.NAME);
String myId = itemID.getText().toString();
String myTitle = itemTitle.getText().toString();
String myDesc = itemDesc.getText().toString();
Intent intent = new Intent(calling_activity, ModifyActivity.class);
intent.putExtra("Id", myId);
intent.putExtra("Title", myTitle);
intent.putExtra("Desc", myDesc);
calling_activity.startActivity(intent);
}
});
}
}
and in my Lights activity :
#Override
public void myOnCheckedChangedHandler(String id, boolean check_status) {
Toast.makeText(
this,
"You changed the status for the row with an id of " + id +
" the status is now " + new Boolean(check_status).toString(),
Toast.LENGTH_SHORT).show();
String name = cursor.getString(cursor.getColumnIndex(dbHelper.DESC));
if(new Boolean(check_status).toString().equals("true")){
Toast.makeText(this,name +" is ON", Toast.LENGTH_SHORT).show();
}
}
Please manage through if/else case inside bindView at adapter, You need to check the switch condition like below :
// set the code into bind
if(switchCondition1 == 1)
{
//set the code as per condition wise
}else{
//
}
After change the state you also need to change the state into your list item and use notifydatasetChanged() method to refresh the list items.

SetChecked RadioButton of SingleChoice ListView on Activity Launch

I've been working on creating a single choice ListView populated by a custom ArrayAdapter (which works), except I need to set a pre-determined RadioButton in the ListView as setChecked(true) when the activity launches.
I'm populating my ListView with a List<Server> servers object at inflation that contains a boolean 'default_server' used to determine which row / RadioButton should be setChecked(true).
Selecting the various ListView items after the activity has launched correctly flags the specific RadioButton as setChecked(true) in Single Choice mode as desired.
My code:
ServerActivity.java
public class ServersActivity extends FragmentActivity
//FragmentActivity needed to display dialog fragment when ListView item clicked
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server_list);
servers = getServers();
lv = (ListView) findViewById(android.R.id.list);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
adapter = new ServerActivityArrayAdapter(this, R.layout.server_list_item, servers);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// show dialog if not long clicked
if (!longClicked) {
lv.setItemChecked(position, true);
showServerDialog(position);
}
}
});
}
ServerActivityArrayAdapter.java
public class ServerActivityArrayAdapter extends ArrayAdapter<Server> {
private int layout;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private static LayoutInflater inflater;
public ServerActivityArrayAdapter(Context context, int layout, List<Server> servers) {
super(context, layout, servers);
ListArrays listArrays = new ListArrays(context);
this.layout = layout;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private static class ServerViewHolder {
private TextView textView;
private RadioButton radioButton;
public ServerViewHolder() {
// EMPTY DEFAULT CONSTRUCTOR
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Server server = this.getItem(position);
final ServerViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(layout, parent, false);
viewHolder = new ServerViewHolder();
viewHolder.textView = (TextView) convertView.findViewById(R.id.tvServerName);
viewHolder.radioButton = (RadioButton) convertView.findViewById(R.id.rbDefault);
convertView.setTag(viewHolder);
} else {
viewHolder = (ServerViewHolder) convertView.getTag();
}
// TODO: SET THE DEFAULT SERVER
viewHolder.radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position != mSelectedPosition && mSelectedRB != null) {
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
notifyDataSetChanged();
mSelectedRB = (RadioButton) v;
server.setDefaultServer(mSelectedRB.isChecked());
}
});
if (mSelectedPosition != position) {
viewHolder.radioButton.setChecked(false);
} else {
viewHolder.radioButton.setChecked(true);
if (mSelectedRB != null && viewHolder.radioButton != mSelectedRB) {
mSelectedRB = viewHolder.radioButton;
}
}
viewHolder.textView.setText(server.getName());
return convertView;
}
}
Again, my List<Server> servers object is populating the ListView, the subsequent dialog popups (when a row is clicked) correctly and the RadioButtons on each row are currently functioning in Single Choice mode. I'm using server.setDefaultServer(mSelectedRB.isChecked()); in the setOnClickListener of ServerActivityArrayAdapter to update which server has default_server(true).
Everything I've tried so far in the ServerActivityArrayAdapter seems to break the Single Choice mode requirement of the RadioButton. How can I fix this?
I did go back and implement Shared Preferences into my project as Mridul suggested, but the solution really didn't require them.
Basically, I updated the constructor of my ServerActivityArrayAdapter class to let me pass the ID of the default server from the ServerActivity class when it's created. Also, I set mSelectionPostion = defServer, so the correct RadioButton in my ListView is checked when everything is inflated.
public ServerActivityArrayAdapter(Context context, int layout, List<Server> servers, int defServer) {
super(context, layout, servers);
ListArrays listArrays = new ListArrays(context);
this.layout = layout;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSelectedPosition = defServer;
}

Get parent layout from custom Adapter

Could anybody explain me, how to realize?
I have an activity with listview and footer with some elements(textview).
Listview built with custom adapter. Each listview item has few elements. And my question: how can i change textview in footer, from custom adapter, when i clicking on some listview's element?
Thx a lot!
/**** My adapter ****/
public class MyListAdapter extends ArrayAdapter<Product> implements UndoAdapter {
private final Context mContext;
private HashMap<Product, Integer> mIdMap = new HashMap<Product, Integer>();
ArrayList<Product> products = new ArrayList<Product>();
final int INVALID_ID = -1;
LayoutInflater lInflater;
String imagePath;
public MyListAdapter(Context context, int textViewResourceId, List<Product> prod) {
//super(context, textViewResourceId, prod);
super(prod);
lInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
for (int i = 0; i < prod.size(); i++) {
//add(prod.get(i));
mIdMap.put(prod.get(i),i);
}
}
#Override
public long getItemId(final int position) {
//return getItem(position).hashCode();
Product item = (Product) getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;;
Product p = getItem(position);
if (convertView == null) {
convertView = lInflater.inflate(R.layout.item, null);
//convertView.setBackgroundResource(R.drawable.rounded_corners);
int currentTheme = Utils.getCurrentTheme(convertView.getContext());
switch (currentTheme) {
case 0:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
case 1:
convertView.setBackgroundResource(R.drawable.border);
break;
default:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
}
holder = new ViewHolder();
holder.tvDescr = (TextView) convertView.findViewById(R.id.tvDescr);
holder.list_image = (ImageView) convertView.findViewById(R.id.list_image);
holder.products_amount = (TextView) convertView.findViewById(R.id.amountDigits);
holder.products_price = (TextView) convertView.findViewById(R.id.priceDigits);
holder.ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
holder.unit = (TextView) convertView.findViewById(R.id.unit);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(p.getProductImageBitmap() != null && p.getProductImageBitmap() != "") {
Log.d("PATH -- ", p.getProductImageBitmap());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
/*.showImageOnLoading(R.id.progress_circular)*/
.build();
imageLoader.displayImage(p.getProductImageBitmap(), holder.list_image, options);
} else {
holder.list_image.setImageResource(R.drawable.ic_launcher);
}
holder.tvDescr.setText(p.getProductName());
holder.ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String deletedItem = getItem(position).getProductName();
MyListAdapter.this.remove(getItem(position));
if (MyListAdapter.this.getCount() > 0) {
Toast.makeText(mContext, deletedItem + " " + mContext.getString(R.string.deleted_item), Toast.LENGTH_SHORT).show();
MyListAdapter.this.notifyDataSetChanged();
} else {
Toast.makeText(mContext,mContext.getString(R.string.sklerolist_empty), Toast.LENGTH_SHORT).show();
}
}
});
//Функционал для большой картинки продукта
//открывается новое активити с большой картинкой
holder.list_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imagePath = getItem(position).getProductImageBitmap();
if(imagePath != null && imagePath != "") {
Pattern normalPrice = Pattern.compile("^file");
Matcher m2 = normalPrice.matcher(imagePath);
if (m2.find()) {
Intent myIntent = new Intent(view.getContext(), ViewImage.class).putExtra("imagePath", imagePath);
view.getContext().startActivity(myIntent);
}
}
}
});
holder.products_price.setText(fmt(p.getProductPrice()));
holder.products_amount.setText(fmt(p.getProductAmount()));
holder.unit.setText(p.getProductUnit());
return convertView;
}
public static String fmt(double d){
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
static class ViewHolder {
ImageView list_image;
TextView tvDescr;
TextView products_amount;
TextView products_price;
TextView unit;
ImageView ivImage;
ProgressBar circleProgress;
}
#NonNull
#Override
public View getUndoView(final int position, final View convertView, #NonNull final ViewGroup parent) {
View view = convertView;
if (view == null) {
//view = LayoutInflater.from(mContext).inflate(R.layout.undo_row, parent, false);
view = lInflater.inflate(R.layout.undo_row, parent, false);
}
return view;
}
#NonNull
#Override
public View getUndoClickView(#NonNull final View view) {
return view.findViewById(R.id.undo_row_undobutton);
}
public View getHeaderView(final int position, final View convertView, final ViewGroup parent) {
TextView view = (TextView) convertView;
//View view = convertView;
if (view == null) {
//view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.list_header, parent, false);
//view = lInflater.inflate(R.layout.list_header, parent, false);
}
//view.setText(mContext.getString(R.string.header, getHeaderId(position)));
return view;
}
public long getHeaderId(final int position) {
return position / 10;
}
}
Your ListView has a listener for the click events on list elements.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something when a list item is clicked
}
But if you want to pas something else back from the adapter to the Activity or the Fragment that contains that ListView and Adapter, you should create a simple interface and set it as listener to your adapter. After that, set click events on your rows from within the adapter, and notify the Activity or Fragment using your own interface.
For example you have the interface defined like this
public interface OnItemClickedCustomAdapter {
public void onClick(ItemPosition position);
}
and in your Adapter class you will have a private member
private OnItemClickedCustomAdapter mListener;
and a method used to set the listener
public void setOnItemClickedCustomAdapter(OnItemClickedCustomAdapter listener){
this.mListener = listener;
}
From your Activity or Fragment where your ListView is defined, and your adapter is set, you will be able to call setOnItemClickedCustomAdapter with this as parameter, and there you go. Your activity will now listen for your events. To trigger an event, just call mListener.onClick() from your custom adapter. You can pass back data you need back to the Activity or Fragment, and from there you have access to your Header or Footer directly, and you can change the text on them.

Android JSON Data not parsing into ListView

Android not parsing JSON data into ListView, I am using this tutorial and just made few changes in ListViewAdapter.java
Like in my new implementation i used ViewHolder, and my code looks like this:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
ViewHolder holder;
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
static class ViewHolder {
public ViewHolder(View convertView) {
// TODO Auto-generated constructor stub
}
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
// Avoid unneccessary calls to findViewById() on each row, which is expensive!
holder = null;
/*
* If convertView is not null, we can reuse it directly, no inflation required!
* We only inflate a new View when the convertView is null.
*/
if (convertView == null) {
convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.listview_item, null);
// Create a ViewHolder and store references to the two children views
holder = new ViewHolder(convertView);
holder.rank = (TextView) convertView.findViewById(R.id.rank);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.population = (TextView) convertView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) convertView.findViewById(R.id.flag);
// The tag can be any Object, this just happens to be the ViewHolder
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Capture position and set results to the TextViews
holder.rank.setText(resultp.get(MainActivity.RANK));
holder.country.setText(resultp.get(MainActivity.COUNTRY));
holder.population.setText(resultp.get(MainActivity.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), holder.flag);
// Capture ListView item click
return convertView;
}
}
Edited: Click on ListItem code
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// code to handle click
}
});
}
But i don't no why i am not getting data into ListView !
The issue is that you are not assigning the HashMap to `resultp that has the information you want to display
public View getView(final int position, View convertView, ViewGroup parent) {
holder = null;
if (convertView == null) {
convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.listview_item, null);
holder = new ViewHolder(convertView);
holder.rank = (TextView) convertView.findViewById(R.id.rank);
holder.country = (TextView) convertView.findViewById(R.id.country);
holder.population = (TextView) convertView.findViewById(R.id.population);
holder.flag = (ImageView) convertView.findViewById(R.id.flag);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Here's the change
resultp = data.get(position);
// Here's the change
holder.rank.setText(resultp.get(MainActivity.RANK));
holder.country.setText(resultp.get(MainActivity.COUNTRY));
holder.population.setText(resultp.get(MainActivity.POPULATION));
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), holder.flag);
return convertView;
}
To attach OnItemClickListener to your ListView, in the Activity that contains the ListView, add the following:
public class MyActivity implements OnItemClickListener{
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState() {
....
....
// lv initialized here
// adapter of lv set here
attachListeners();
}
private void attachListeners() {
....
....
// attach listeners to other views if you like
lv.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// code to handle click
}
}
Or, if you don't want your Activity to implement OnItemClickListener, then,
public class MyActivity {
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState() {
....
....
// lv initialized here
// adapter of lv set here
attachListeners();
}
private void attachListeners() {
....
....
// attach listeners to other views if you like
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// code to handle click
}
});
}
}
First of all try to fix this:
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}

ListView Updating a single row

I want to update a single row in my listview with different content once i press a button. I know i can use notifydatasetchanged() but that would update the whole listView.
I have read this answer and it fits perfectly for what I want to do.
I have done a listview with 5 rows and when I press the button I want to update the 4th row with a different text. I dont want to set the text programatically since this is just a dummy project just to see if refreshing a single row is possible and my real project is much more complex than just a textview.
So my question is: can i use getView() to update a single row in a listview?
Here is my code:
my Activity:
public class MainActivity extends Activity {
public ListView list1;
public listAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list1 = (ListView) findViewById(R.id.my_list);
adapter = new listAdapter(this);
list1.setAdapter(adapter);
Button button1 = (Button) findViewById(R.id.my_button);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
adapter.setText("Different text");
View row2Update = list1.getChildAt(3);
list1.getAdapter().getView(3, row2Update, list1);
}
});
}
}
My adapter :
public class listAdapter extends BaseAdapter{
public Activity activity;
public String text="Normal Text";
public listAdapter(Activity activity){
this.activity = activity;
}
public void setText(String text){
this.text = text;
}
public int getCount() {
return 5;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
LinearLayout rowView = (LinearLayout) inflater.inflate(R.layout.row_layout, null);
TextView textView = (TextView) rowView.findViewById(R.id.row_text);
textView.setText(text);
return rowView;
}
}
This is what the activity looks like:
But when I press my button nothing changes
You cannot call the getView() method of the adapter yourself. The adapter's getView() method is is only called, when
The listview is create
when the user scrolls the list view
when notifysetdatachanged() is called.
All these are done by the OS. GetView() is called for all the rows in the listview. It is not called for just a single row. So, if you want to change the rows, you have to provide the data again in a String[], ArrayList<> etc
If you want different text to appear for for a single row, onClick() of a button - you can do this
public class listAdapter extends BaseAdapter{
public Activity activity;
public ArrayList<String> text;
public listAdapter(Activity activity){
this.activity = activity;
}
public void setText(ArrayList<String> text){
this.text = text;
}
public int getCount() {
return 5;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
LinearLayout rowView = (LinearLayout) inflater.inflate(R.layout.row_layout, null);
TextView textView = (TextView) rowView.findViewById(R.id.row_text);
textView.setText(text[position]);
return rowView;
}
}
And in your Activity :
list1 = (ListView) findViewById(R.id.my_list);
adapter = new listAdapter(this);
String[] entries={"Normal Text","Normal Text","Normal Text","Normal text","Normal text"};
ArrayList<String> text=Arrays.asList(entries);
adapter.setText(text);
list1.setAdapter(adapter);
Button button1 = (Button) findViewById(R.id.my_button);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
text.set(3,"Different Text");
adapter.setText(text);
list1.setAdapter(adapter);
}
});
There is another way of doing it also as #Andy suggested in one of the comments :
listViewPeople.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long l) {
//IF YOU WANT TO CHANGE THE CONTENT OF THE ROW CLICKED
if(position == someNumber) {
text.set(position,"different Text");
list1.setAdapter(text);
}
}
});
Sorry for the bold text. For some reason the CTRL+K is not working for the above code.

Categories

Resources