I have a ListActivity and a custom adapter that extends BaseAdapter.
On each row of the ListView, there is a button and a few more views. onClickListener is declared in the adapter.
How can I refresh list view after button is clicked ?
Here is the code
List Activity:
.........
super.onCreate(savedInstanceState);
here im reading content from a file and then creating adapter with that content
adapter = new UvArrayAdapter(this, strarray3, strarray2, intarray);
setListAdapter(adapter);
..........
Adapter:
.......
public class UvArrayAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater linflater;
private TextView txt_1, txt_2, txt_3;
private ProgressBar pr1;
private String[] str1;
private String[] str2;
private String[] str3;
private Integer[] int1;
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
Log.v("TAG", "onItemClick at position" + mPosition);
}
}
public UvArrayAdapter(Context context, String[] s1, String[] s2, Integer[] i1) {
mContext = context;
str1 = s1;
str2 = s2;
int1 = i1;
linflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return str1.length;
}
#Override
public Object getItem(int arg0) {
return str1[arg0];
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = linflater.inflate(R.layout.uv_rowlayout, null);
}
convertView.setOnClickListener(new OnItemClickListener(position));
txt_1 = (TextView) convertView.findViewById(R.id.textView1);
pr1 = (ProgressBar) convertView.findViewById(R.id.progressBar1);
pr1.setProgress(int1[position]);
txt_1.setText(str1[position]);
txt_2 = (TextView) convertView.findViewById(R.id.textView2);
txt_2.setText(str2[position]+"mV");
Button btn = (Button) convertView.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Log.v("onClickListener", "button - clicked at position " position);
do some changes in mentioned file and after that i need to update the list view with new data
}});
return convertView;
}
}
adapter.notifyDataSetChanged(); // to notify the adapter that your data has been updated
Note: If you get any errors with the above line, you could try the following code (where mListView is the name of my ListView object)
((BaseAdapter) mListView.getAdapter()).notifyDataSetChanged();
Another way would be to invalidate the List so that it is redrawn form the updated data set once again.
mListView=(ListView) findViewById(R.id.MyListView);
mListView.invalidate();
Use notifyDataSetChanged()
adapter = new UvArrayAdapter(this, strarray3, strarray2, intarray);
setListAdapter(adapter);
UvArrayAdapter.notifyDataSetChanged();
// To make the adapter aware of the changes
Related
I am an intern at this company and I have a task assigned to me by my team leader where I need to make an app that displays a list of items that I can add to and edit/delete the items on the list. I am following the requirements given to me on what the app needs to do.
The problem I'm having is that I need to pass values from an item when clicked on a ListView which uses a custom adapter, and have them sent to a new activity and displayed on the new activity's textviews and imageview. I have tried using putExtras() methods in the list click method and getting the values using getExtras() methods but they didn't work and I've already deleted those codes, so they are no longer there. If you need more of the classes/activities I'm using please let me know. I am using Android Studio 3.1.4
ItemListView.java
public class ItemListView extends AppCompatActivity {
DatabaseHelper myDB;
ArrayList<Item> itemList;
ListView listView;
Item item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list_view);
listView = (ListView) findViewById(R.id.listView);
myDB = new DatabaseHelper(this);
itemList = new ArrayList<>();
Cursor data = myDB.getListContents();
int numRows = data.getCount();
if(numRows == 0){
Toast.makeText(ItemListView.this, "There is nothing in the database.", Toast.LENGTH_LONG).show();
} else {
while(data.moveToNext()){
item = new Item(data.getString(1), data.getString(2), data.getString(3));
itemList.add(item);
}
Row_ListAdapter adapter = new Row_ListAdapter(this, R.layout.list_adapter_view, itemList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
startActivity(intent);
}
});
}
ViewItemClicked.java
I want the values displayed onto the layout of this activity when a row is clicked.
public class ViewItemClicked extends AppCompatActivity {
ImageView image;
TextView name, desc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_item_clicked);
}
}
Other classes I used:
Row_ListAdapter.java
public class Row_ListAdapter extends ArrayAdapter<Item> {
private LayoutInflater mInflater;
private ArrayList<Item> items;
private int mViewResourceId;
ImageView image;
TextView name;
TextView description;
public Row_ListAdapter(Context context, int textViewResourceId, ArrayList<Item> items){
super(context, textViewResourceId, items);
this.items = items;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents){
convertView = mInflater.inflate(mViewResourceId, null);
Item item = items.get(position);
if(item != null){
image = (ImageView) convertView.findViewById(R.id.iconIV);
name = (TextView) convertView.findViewById(R.id.nameTV);
description = (TextView) convertView.findViewById(R.id.descTV);
if(image != null){
image.setImageBitmap(item.getImage());
}
if(name != null){
name.setText(item.getName());
}
if(description != null){
description.setText(item.getDescription());
}
}
return convertView;
}
}
Link to GUI: https://i.stack.imgur.com/wHfgv.png
Before you pass the data, implement your Item Class with Serializable like this:
public class Item implements Serializable{
/*your class code here*/
}
Then pass the data in the listView.setOnItemClicklistener like this
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Item passItem = itemList.get(position);
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
Bundle itemBundle = new Bundle();
itemBundle.putSerializable("dataItem",passItem)// put the data and define the key
intent.putExtras(itemBundle)
startActivity(intent);
}
});
and to open the data in the ViewItemClicked.Class
public class ViewItemClicked extends AppCompatActivity {
ImageView image;
TextView name, desc;
Item item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
item = (Item) getIntent().getSerializableExtra("dataItem"); // use the key
setContentView(R.layout.activity_view_item_clicked);
/*now u can use the item data*/
}
}
Try the codes below:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
String name = itemList.get(position).getString(1);
String description = itemList.get(position).getString(2);
String something_else = itemList.get(position).getString(3);
intent.putExtra("name", name);
intent.putExtra("description", description);
intent.putExtra("something_else", something_else);
startActivity(intent);
}
In your Details Activity:
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String description = intent.getStringExtra("description");
String something_else = intent.getStringExtra("something_else");
Now use the strings to show the values in the desired places.
as
edittext.setText(name);
WHAT FORMAT TYPE OF IMAGE YOUR ARE USING
Is it Base64 or Bitmap if it is Base64 try this code..
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ItemListView.this, ViewItemClicked.class);
String name = list.get(position).getName();
String description = list.get(position).getDescription();
String image= list.get(position).getImage();
startActivity(intent);
}
In Your Second Activity use this code..
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String description = intent.getStringExtra("description");
String image = intent.getStringExtra("image");
Convert here Base64 to Bitmap..
byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
Define an interface for listening item click event
public class Row_ListAdapter extends ArrayAdapter<Item> {
private LayoutInflater mInflater;
private ArrayList<Item> items;
private int mViewResourceId;
ImageView image;
TextView name;
TextView description;
OnItemListener mListener;
public Row_ListAdapter(Context context, int textViewResourceId, ArrayList<Item> items){
super(context, textViewResourceId, items);
this.items = items;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents){
convertView = mInflater.inflate(mViewResourceId, null);
Item item = items.get(position);
if(item != null){
image = (ImageView) convertView.findViewById(R.id.iconIV);
name = (TextView) convertView.findViewById(R.id.nameTV);
description = (TextView) convertView.findViewById(R.id.descTV);
if(image != null){
image.setImageBitmap(item.getImage());
}
if(name != null){
name.setText(item.getName());
}
if(description != null){
description.setText(item.getDescription());
}
}
convertView.setOnClickListener((v) -> {
if(mListener != null) {
mListener.onItemClick(v, item);
}
})
return convertView;
}
public void setOnItemListener(OnItemListener listener) {
mListener = listener;
}
public interface OnItemClickListener {
void onItemClick(View v, Item item);
}
}
Then, implement OnItemClickListener in the activity and set it to the adapter:
Row_ListAdapter adapter = new Row_ListAdapter(this, R.layout.list_adapter_view, itemList);
adapter.setOnItemListener("your implement");
Currently I'm adding a custom row (contains and edit text and a plus and minus for adding/removing a row) to a list view. However, each time a row is added the contents from all edit texts are wiped.
public class ingredientView extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public ingredientView(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.ingredient_item, null);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, loadedFood);
//Handle TextView and display string from your list
InstantAutoComplete listItemText = (InstantAutoComplete) view.findViewById(R.id.recipe_ingredients);
listItemText.setAdapter(adapter);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)view.findViewById(R.id.ingredient_minus_button);
ImageButton addBtn = (ImageButton)view.findViewById(R.id.ingredient_plus_button);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
if (list.size()>1){
list.remove(position); //or some other task
notifyDataSetChanged();}
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.add(position+1,"");
notifyDataSetChanged();
}
});
return view;
}
private static final String[] loadedFood = new String[]{
"eggs","milk","butter","flour"
};
}
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.
I want to add a new row on clicking add button in a list view in android.
Can someone help me out?
Here is the code I have so far:
public class prsnlhstry<EventArgs> extends Activity implements OnItemClickListener {
public static ArrayList<String> arr_sort_textview1= null;
public static ArrayList<String> arr_sort_textview2=null;
public static ArrayList<String> arr_sort_textview3=null;
public Resources ApptResources= null;
private ContextWrapper mycontext;
tododata todo;
int clickcounter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv= (ListView)findViewById(R.id.listview);
todo = new tododata(this);
List<listObject> List = new ArrayList<listObject>();
for(int i = 0; i <= 5; i++){
listObject lo = new listObject();
lo.grade = Integer.toString(i);
lo.reason = Integer.toString(i);
lo.school = Integer.toString(i);
List.add(lo);
}
CustomAdapter ca = new CustomAdapter(this);
lv = (ListView)findViewById(R.id.listview);
lv.setAdapter(ca);
lv.setOnItemClickListener(this);
ca.notifyDataSetChanged();
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Toast.makeText(prsnlhstry.this, "Row Added Successfully", Toast.LENGTH_SHORT).show();
}
});
}
private class listObject {
String grade;
String school;
String reason;
}
public class CustomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return todo.getLength();
}
#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 parent) {
ViewHolder holder;
String temp = null;
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.grid_item, null);
// Creates a ViewHolder and store references to the views
// we want to bind data to.
holder = new ViewHolder();
holder.textview1 = (TextView) convertView.findViewById(R.id.item2);
holder.textview2 = (TextView) convertView.findViewById(R.id.item3);
holder.textview3 = (TextView) convertView.findViewById(R.id.item4);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textview1.setText(todo.getgrade(position));
holder.textview2.setText(todo.getschool(position));
holder.textview3.setText(todo.getreason(position));
return convertView;
}
}
static class ViewHolder {
TextView textview1;
TextView textview2;
TextView textview3;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
}
Just add the item to your list and refresh the adapter, nothing special.
You need to increment your "tododata" data structure on button click and then call to notifyDataSetChanged() method:
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
todo.addNewRow();
ca.notifyDataSetChanged();
Toast.makeText(prsnlhstry.this, "Row Added Successfully", Toast.LENGTH_SHORT).show();
}
});
To compile the above code you will need to define "ca" variable as the final one, or make it class member.
I hope it helps.
here i call the customdialog through my parent activity.. where as the dialog is in another activity contains listview...from that dialog i transfer a selected content from listview.. but fail to achieve my target.. and tried so many way.. can any one assist me to achieve it.
Note: i got error in on listitemclick listener...
customdialog.class
public class CustomizeDialog extends Dialog {
org.me.dailogfrmchildact.MainActivity ma;
Button cancelButton;
ListView list;
int item_pos;
public CustomizeDialog(Context context) {
super(context);
Context cs = context;
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog);
ma=new MainActivity();
list = (ListView) findViewById(R.id.list);
cancelButton = (Button) findViewById(R.id.OkButton);
ListviewContent.add("item1");
ListviewCount.add("20");
ListviewContent.add("item2");
ListviewCount.add("30");
list.setAdapter(new ListViewAdapter(cs));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
item_pos = pos;
System.out.println("===========item_pos" + pos);
ma.txt.setText(ListviewContent.get(pos).toString());
dismiss();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
dismiss();
}
});
}
private static ArrayList<String> ListviewContent = new ArrayList<String>();
private static ArrayList<String> ListviewCount = new ArrayList<String>();
private static class ListViewAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ListViewAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return ListviewContent.size();
}
public Object getItem(int position) {
return position;
}
public String getCount(int position) {
return ListviewCount.get(position);
}
public String[] getSizeType(int position) {
String[] str = new String[2];
str[0] = ListviewContent.get(position);
str[1] = ListviewCount.get(position);
return str;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ListContent holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listviewinflate, null);
holder = new ListContent();
holder.text = (TextView) convertView.findViewById(R.id.TextView01);
holder.text.setCompoundDrawables(null, null, null, null);
holder.count = (TextView) convertView.findViewById(R.id.TextView02);
holder.count.setCompoundDrawables(null, null, null, null);
convertView.setTag(holder);
} else {
holder = (ListContent) convertView.getTag();
}
holder.text.setText(ListviewContent.get(position));
holder.count.setText(ListviewCount.get(position));
return convertView;
}
static class ListContent {
TextView text;
TextView count;
}
}
}
mainactivity.class:
public class MainActivity extends Activity {
org.me.dailogfrmchildact.CustomizeDialog cd;
Button btn;
EditText txt;
CustomizeDialog customizeDialog;
boolean click = false;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
cd = new CustomizeDialog(this);
btn = (Button) findViewById(R.id.btn1);
txt = (EditText) findViewById(R.id.txt1);
/** Display Custom Dialog */
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
customizeDialog = new CustomizeDialog(MainActivity.this);
customizeDialog.show();
}
});
}
}
The problem is you're creating a new MainActivity in your CustomizeDialog when you should be using the one that created the CustomizeDialog in the first place.
Have CustomizeDialog take in a MainActivity instead of Context and set ma equal to that.
Edit:
Change CustomizeDialog's constructor to:
public CustomizeDialog(MainActivity mainActivity) {
super(mainActivity);
ma = mainActivity; // Instead of ma = new MainActivity()
// everything else is the same
}