How to start animation in custom listview - android

I have a custom listview, include an imageview and a textview.
I want, when I click imageview in this, start animation(rotate).
My problem is: When scrolling, animation stopped.
public class AdapterFoodGroups extends BaseAdapter {
private static LayoutInflater mInflater = null;
Context context;
int[] foodImagesId;
String[] foodNameList;
String[] foodDescriptions;
int[] foodTimes;
boolean[] loadAnimation;
public AdapterFoodGroups(Context context, String[] foodNameList, String[] foodDescriptions, int[] foodTimes, int[] foodImagesId) {
// TODO Auto-generated constructor stub
this.foodNameList = foodNameList;
this.foodDescriptions = foodDescriptions;
this.foodTimes = foodTimes;
this.foodImagesId = foodImagesId;
this.context = context;
loadAnimation = new boolean[foodNameList.length];
for (boolean b: loadAnimation) {
b = false;
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder viewHolder;
final RotateAnimation anim = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5 f, Animation.RELATIVE_TO_SELF, 0.5 f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(800);
if (convertView == null) {
mInflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.adapter_foodgroup, null);
viewHolder = new ViewHolder();
viewHolder.txtFoodName = (TextView) convertView.findViewById(R.id.txtFoodNameGrid);
viewHolder.txtFoodDescription = (TextView) convertView.findViewById(R.id.txtFoodDescriptionGrid);
viewHolder.txtFoodTime = (TextView) convertView.findViewById(R.id.txtFoodTimeGrid);
viewHolder.ivFoodImage = (CircularImageView) convertView.findViewById(R.id.ivFoodImageGrid);
viewHolder.ivLoad = (ImageView) convertView.findViewById(R.id.ivLoad);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (this.foodImagesId[position] != 0) {
viewHolder.ivFoodImage.setImageResource(this.foodImagesId[position]);
viewHolder.ivFoodImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, String.valueOf(position) + " = " + foodNameList[position], Toast.LENGTH_LONG).show();
}
});
}
if (this.foodNameList[position] != null) {
viewHolder.txtFoodName.setText(this.foodNameList[position]);
}
if (this.foodDescriptions[position] != null) {
viewHolder.txtFoodDescription.setText(this.foodDescriptions[position]);
}
if (this.foodTimes[position] != 0) {
viewHolder.txtFoodTime.setText(String.valueOf(this.foodTimes[position]) + " دقیقه");
}
viewHolder.ivLoad.setImageResource(R.drawable.load);
viewHolder.ivLoad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.ivLoad.setAnimation(anim);
viewHolder.ivLoad.startAnimation(anim);
}
});
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return foodNameList.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public static class ViewHolder {
public CircularImageView ivFoodImage;
public ImageView ivLoad;
public TextView txtFoodName;
public TextView txtFoodDescription;
public TextView txtFoodTime;
}
}

Try this:
In your adapter constructor change these lines:
....
loadAnimation = new boolean[foodNameList.length];
for (int i=0; i < loadAnimation.length; i++) {
loadAnimation[i] = false;
}
....
In getView() method add this:
...
viewHolder.ivLoad.setImageResource(R.drawable.load);
if(loadAnimation[position]){
viewHolder.ivLoad.setAnimation(anim);
viewHolder.ivLoad.startAnimation(anim);
} else {
viewHolder.ivLoad.setAnimation(null);
}
viewHolder.ivLoad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.ivLoad.setAnimation(anim);
viewHolder.ivLoad.startAnimation(anim);
loadAnimation[position] = true;
}
});
...
Hope it helps!

Related

How to set onclick listener for two Gridview in same layout?

i have two custom GridView, I want to set Onclick Listener for first GridView, i did it inside its adapter , working fine ... but when generate items in second GridView the onclick listener read values from second GridView when i press on item in first GridView!
The onclick listener working fine if the second GridView empty
I have no idea how to fix this
The problem with holder.tvgroup1 and holder.tvgroup_delete_icon
Thanks
First GridView Adapter
public class GroupGeneratedAdapter extends BaseAdapter {
ArrayList<String> result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
GroupGeneratedAdapter(GroupMakerG groupMakerG, ArrayList<String> UserNameinput) {
// TODO Auto-generated constructor stub
result = UserNameinput;
context = groupMakerG;
// imageId=prgmImages;
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tvgroup, tvgroup1;
ImageView tvgroup_delete_icon;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = new Holder();
// View rowView;
if (convertView == null) {
convertView = inflater.inflate(R.layout.group_generated_original, parent, false);
}
holder.tvgroup = (TextView) convertView.findViewById(R.id.tvgroup);
holder.tvgroup1 = (TextView) convertView.findViewById(R.id.tvgroup1);
holder.tvgroup_delete_icon = (ImageView) convertView.findViewById(R.id.tvgroup_delete_icon);
// holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tvgroup.setText(String.valueOf(position + 1) + "-");
holder.tvgroup1.setText(result.get(position));
// holder.img.setImageResource(imageId[position]);
holder.tvgroup_delete_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GroupMakerG.GroupOfNames.remove(position);
GroupMakerG.MainGroup.invalidateViews();
if (GroupMakerG.arraySugestion.size() > 0) {
GroupMakerG.arraySugestion.clear();
GroupMakerG.makeSuggestions();
} else {
GroupMakerG.makeSuggestions();
}
GroupMakerG.GeneratedGroup.setAdapter(null);
GroupMakerG.No_Of_Groups.setText("");
GroupMakerG.numoftries = 0;
GroupMakerG.Group_num_tries.setText("0");
GroupMakerG.GroupNameLength.setText(String.valueOf(GroupMakerG.GroupOfNames.size()));
}
});
holder.tvgroup1.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context );
builder.setTitle("Modify Item No." + " " + (position + 1));
// I'm using fragment here so I'm using getView() to provide ViewGroup
// but you can provide here any other instance of ViewGroup from your Fragment / Activity
View viewInflated = LayoutInflater.from(context).inflate(R.layout.modify_name_mainlist, (ViewGroup) parent.findViewById(android.R.id.content), false);
// Set up the input
final EditText input = (EditText) viewInflated.findViewById(R.id.client_name_input);
input.setText(GroupMakerG.GroupOfNames.get(position));
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
String m_Text = input.getText().toString();
if (m_Text.trim().equals("")) {
// Toast.makeText(context, "You should enter name", Toast.LENGTH_SHORT).show();
Toast toast = Toast.makeText(context,context.getString(R.string.group_you_should_enter_name), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else {
GroupMakerG.GroupOfNames.set(position, m_Text);
GroupMakerG.MainGroup.invalidateViews();
GroupMakerG.GeneratedGroup.setAdapter(null);
GroupMakerG.numoftries = 0;
GroupMakerG.Group_num_tries.setText("0");
Toast toast = Toast.makeText(context, context.getString(R.string.group_item_changed), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return false;
}
});
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(context, "You Clicked "+ result.get(position), Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
Second GridView Adapter
public class GroupGeneratedAdapterG extends BaseAdapter {
private ArrayList<String> resultg;
int[] imageId;
private static LayoutInflater inflaterg = null;
private static int generated_group_counter;
Context contextg;
GroupGeneratedAdapterG(GroupMakerG groupMaker, ArrayList<String> UserNameoutput) {
// TODO Auto-generated constructor stub
resultg = UserNameoutput;
contextg = groupMaker;
// imageId=prgmImages;
inflaterg = (LayoutInflater) contextg.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
generated_group_counter = 0;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return resultg.size();
}
#Override
public Object getItem(int positiong) {
// TODO Auto-generated method stub
return positiong;
}
#Override
public long getItemId(int positiong) {
// TODO Auto-generated method stub
return positiong;
}
public class Holder {
TextView tvgroupg, tvgroup1g;
// ImageView img;
}
#Override
public View getView(final int positiong, View convertViewg, ViewGroup parentg) {
// TODO Auto-generated method stub
generated_group_counter = generated_group_counter + 1;
Holder holderg = new Holder();
// View rowView;
if (convertViewg == null) {
convertViewg = inflaterg.inflate(R.layout.group_generated_generated, parentg, false);
}
holderg.tvgroupg = (TextView) convertViewg.findViewById(R.id.tvgroupg);
holderg.tvgroup1g = (TextView) convertViewg.findViewById(R.id.tvgroup1g);
// holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
String[] ary = resultg.get(positiong).split("!##%");
if (ary[1].length() > 4) {
if (ary[1].substring(0, 5).equals("Group")) {
holderg.tvgroupg.setText("");
holderg.tvgroup1g.setText(ary[1]);
} else {
holderg.tvgroupg.setText(ary[0]);
holderg.tvgroup1g.setText(ary[1]);
}
} else {
holderg.tvgroupg.setText(ary[0]);
holderg.tvgroup1g.setText(ary[1]);
}
convertViewg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(contextg, "You Clicked "+ String.valueOf(resultg.get(positiong)), Toast.LENGTH_LONG).show();
}
});
return convertViewg;
}
}

How to select two list items at same time ? To be specific ONLY TWO items not more than that

I have a list view like the below image.
Now I want to select Only Any two items from the list view at a time and pass the values of both listview items with Intent to next activity. How can I achieve it.?
If Both items are not selected set validation on it?
AdapterClass
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.img= (ImageView)convertView.findViewById(R.id.img);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.img.setBackgroundResource(R.drawble.myimg)
}
else
{
// for not selected row
}
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
ImageView img;
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}
}
Main Class
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class LoadChart extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private SwipeListView listView;
DBHelper mydb;
Button det;
LoadAdapter loadAdapter;
ArrayList<DataBase> array_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_chart);
mydb = new DBHelper(this);
array_list = mydb.getAllCotacts();
Log.e("logging", String.valueOf(array_list));
// ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.load_chart_item,R.id.text, array_list);
det = (Button)findViewById(R.id.reli);
listView = (SwipeListView) findViewById(R.id.listview);
listView.setAdapter(new LoadAdapter(getApplicationContext(),array_list));
det.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "";
str = relationAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}
});
listView.setSwipeListViewListener(new BaseSwipeListViewListener() {
int openItem = -1;
int lastOpenedItem = -1;
int lastClosedItem = -1;
#Override
public void onOpened(int position, boolean toRight) {
lastOpenedItem = position;
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!toRight) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
if (openItem > -1 && lastOpenedItem != lastClosedItem) {
listView.closeAnimate(openItem);
}
openItem = position;
}
#Override
public void onStartClose(int position, boolean right) {
Log.d("swipe", String.format("onStartClose %d", position));
lastClosedItem = position;
}
#Override
public void onClosed(int position, boolean fromRight) {
int index = position - listView.getFirstVisiblePosition();
View view = listView.getChildAt(index);
Button delete = (Button) view.findViewById(R.id.btn_delete);
Button edit = (Button) view.findViewById(R.id.btn_edit);
if (!fromRight) {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
#Override
public void onListChanged() {
}
#Override
public void onMove(int position, float x) {
}
#Override
public void onStartOpen(int position, int action, boolean right) {
}
#Override
public void onClickFrontView(int position) {
int id_To_Search = position;
DataBase test = array_list.get(position);
String id = test.getId();
String name = test.getName();
String loc = test.getLocation();
String dt = test.getDate();
String time = test.getTime();
Bundle dataBundle = new Bundle();
dataBundle.putString("name",name);
dataBundle.putString("date",dt);
dataBundle.putString("time",time);
dataBundle.putString("location",loc);
dataBundle.putInt("id", Integer.parseInt(id));
Intent intent = new Intent(getApplicationContext(),LoadedChart.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
#Override
public void onClickBackView(int position) {
Log.e("swipe", String.format("onClickBackView %d", position));
}
#Override
public void onDismiss(int[] reverseSortedPositions) {
}
});
}
public int convertDpToPixel(float dp) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return (int) px;
}
#Override
public void onResume()
{
super.onResume();
Set_Referash_Data();
}
public void Set_Referash_Data() {
array_list.clear();
mydb = new DBHelper(this);
ArrayList<DataBase> con = mydb.getAllCotacts();
for (int i = 0; i < con.size(); i++) {
String tidno = con.get(i).getId();
String name = con.get(i).getName();
String cons = con.get(i).getCon();
String loc = con.get(i).getLocation();
DataBase cnt = new DataBase();
cnt.setId(tidno);
cnt.setName(name);
cnt.setCon(cons);
cnt.setLocation(loc);
array_list.add(cnt);
Log.e(String.valueOf(array_list),"RefreshData");
}
mydb.close();
array_list = mydb.getAllCotacts(); //reload the items from database
LoadAdapter ld = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(ld);
ld.refresh(array_list);
ld.notifyDataSetChanged();
Log.e(String.valueOf(array_list),"RefreshData Final");
}
}
Logcat
05-09 14:47:50.706 29939-29939/com.example.user.humandesignsample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.humandesignsample, PID: 29939
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.user.humandesignsample.RelationAdapter.getSelected()' on a null object reference
at com.example.user.humandesignsample.RelationShipChartList$1.onClick(RelationShipChartList.java:45)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I would use Action Mode with MultiChoiceModeListener.
http://developer.android.com/reference/android/widget/AbsListView.MultiChoiceModeListener.html
There is a callback onItemCheckedStateChanged(ActionMode mode, int position, boolean checked).
You can easily get values of already checked list items ListView.getCheckedItemPositions. So you can prevent selection, if you already selected two or even at once pass the values(or ids) of selected ones without any effort.
You can simply put a counter on item selection.
Take a variable say for ex.
int count = 0;
Check this variable before marking item as selected/deselected:
if(item.isSelected())
{
// you need to make is disable
if(count>0)
{
count--;
// // mark item as deselected
}
}
else
{
// make it selected
if(count<2)
{
count++;
// mark item as selected
}
}
This will make you select ONLY TWO items at a time.
Modify your adapter like this:
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
ArrayList<Boolean> selected = new ArrayList<>();
private int count=0;
public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
mContext = context;
mProductItems = arrayList;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < arrayList.size(); i++) {
selected.add(false);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.e("testtt", String.valueOf(mProductItems.size()));
return mProductItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
holder.location = (TextView)convertView.findViewById(R.id.loc);
holder.btn_delete.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
mydb = new DBHelper(mContext);
stringItem = mProductItems.get(position);
if (stringItem != null) {
if (holder.txtv_name != null) {
holder.txtv_name.setText(stringItem.getName());
holder.nameid.setText(stringItem.getId());
holder.location.setText(stringItem.getLocation());
Log.e("saved Location values",stringItem.getLocation());
}
}
if(selected.get(position))
{
//for selected row
holder.txtv_name.setTextColor(color.red);
}
else
{
// for not selected row
holder.txtv_name.setTextColor(color.black);
}
holder.txtv_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.txtv_name.getCurrentTextColor()== R.color.black)
{
//is not selected
if(count<2)
{
count++;
selected.set(position,true);
// mark item as selected
}
}
else
{
//is selected
if(count>0)
{
count--;
selected.set(position,false);
// // mark item as deselected
}
}
notifyDataSetChanged();
}
});
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBase test = mProductItems.get(position);
String id = test.getId();
mydb.deleteContact(Integer.valueOf(id));
mProductItems.remove(mProductItems.get(position));
LoadAdapter.this.notifyDataSetChanged();
if (mProductItems.size() == 0){
mProductItems.clear();
LoadAdapter.this.notifyDataSetChanged();
}
}
});
Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edi = preff.edit();
edi.putString("key",String.valueOf(position+1));
edi.apply();
mContext.startActivity(intent);
}
});
return convertView;
}
public void refresh(ArrayList<DataBase> items)
{
this.mProductItems = items;
notifyDataSetChanged();
}
private static class ViewHolder {
TextView txtv_name,nameid,location;
Button btn_delete,btn_edit;
}}
EDIT 2: For getting selected items from adapter define below method in
adapter and call it with an adapter object like : adp.getSelected()
public String getSelected() {
String selectedString = "";
int num=0;
for (int i = 0; i < selected.size(); i++) {
if (selected.get(i)) {
num++;
if (num == 1) {
selectedString = mProductItems.get(i).getName();
} else {
selectedString += "," + mProductItems.get(i).getName();
}
}
}
return selectedString;
}
Answer to issue 2 : If you want to use ImageView instead of text color change. The do the same things as above but replace the TextView + Color with ImageView + Image.
EDIT 3:
You have called the getSelected() method from a Null object. Modify your code like this:
listView = (SwipeListView) findViewById(R.id.listview);
loadAdapter = new LoadAdapter(getApplicationContext(),array_list);
listView.setAdapter(loadAdapter);
det.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = "";
str = loadAdapter.getSelected();
Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();
}

Custom listview in Textview Value change by Scrolling

This Is my Adapter problem was scroll listview to change textview value by every position how to solve it ? plus click event to increment one and minus event to decrment and set value in textview (Plus click to quantity + 1 , minus click to quantity - 1).
public class CustomListViewDrycleaning extends BaseAdapter {
ArrayList<ProductModel> myList = new ArrayList<ProductModel>();
LayoutInflater inflater;
Context context;
int loader = R.drawable.loader;
int minteger = 0;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
String rem, b;
private DisplayImageOptions options;
ProductModel currentListData;
String cid, qcount;
public CustomListViewDrycleaning(Context context, ArrayList<ProductModel> list) {
this.myList = list;
this.context = context;
inflater = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_launcher) .showImageForEmptyUri(R.drawable.ic_launcher).showImageOnFail(R.drawable.ic_launcher) .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).build();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return myList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return myList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.customproductlistdrycleaning, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
currentListData = myList.get(position);
mViewHolder.btndropdown.setTag(currentListData.getCategoryId());
mViewHolder.name.setText(currentListData.getName());
mViewHolder.prize.setText("$" + currentListData.getCharge());
mViewHolder.name.setTag(currentListData.getCategoryId());
mViewHolder.plus.setTag(currentListData.getCategoryId());
mViewHolder.minus.setTag(currentListData.getCategoryId());
String img_path = currentListData.getImage();
ImageLoader.getInstance().displayImage(img_path, mViewHolder.imgbucket, options, animateFirstListener);
String servicecheck1 = currentListData.getServiceId1();
String servicecheck2 = currentListData.getServiceId2();
String servicecheck3 = currentListData.getServiceId3();
if (servicecheck1 == null) {
mViewHolder.btndropdown.setVisibility(View.GONE);
} else {
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
}
mViewHolder.btndropdown.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewHolder.lnrbelowdry.setVisibility(View.VISIBLE);
mViewHolder.btndropdown.setVisibility(View.GONE);
mViewHolder.btndropdown1.setVisibility(View.VISIBLE);
}
});
mViewHolder.btndropdown1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewHolder.lnrbelowdry.setVisibility(View.GONE);
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
mViewHolder.btndropdown1.setVisibility(View.GONE);
}
});
if (servicecheck1 == null) {
mViewHolder.btndropdown.setVisibility(View.GONE);
mViewHolder.lnrproduct1.setVisibility(View.GONE);
} else {
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
mViewHolder.lnrproduct1.setVisibility(View.VISIBLE);
mViewHolder.checkBox1.setText(currentListData.getServiceName1());
mViewHolder.txtproductprize1.setText("$" + currentListData.getServiceCharge1());
}
if (servicecheck2 == null) {
mViewHolder.lnrproduct2.setVisibility(View.GONE);
} else {
mViewHolder.lnrproduct2.setVisibility(View.VISIBLE);
mViewHolder.checkBox2.setText(currentListData.getServiceName2());
mViewHolder.txtproductprize2.setText("$" + currentListData.getServiceCharge2());
}
if (servicecheck3 == null) {
mViewHolder.lnrproduct3.setVisibility(View.GONE);
} else {
mViewHolder.lnrproduct3.setVisibility(View.VISIBLE);
mViewHolder.checkBox3.setText(currentListData.getServiceName3());
mViewHolder.txtproductprize3.setText("$" + currentListData.getServiceCharge3());
}
qcount = currentListData.getQuantity();
mViewHolder.plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Utils.COUNTCARTALIST.add(mViewHolder.name.getTag() + "");
int quantityyp = 0;
for (int m = 0; m < Utils.qtylist.size(); m++) {
String ii = mViewHolder.plus.getTag() + "";
Log.e("", "#ii" + ii);
if (mViewHolder.plus.getTag().equals(Utils.qtylist.get(m).get("categoryId"))) {
Toast.makeText(context, "Match", Toast.LENGTH_SHORT).show();
rem = Utils.qtylist.get(m).get("categoryId");
b = Utils.qtylist.get(m).get("quantity");
quantityyp = Integer.parseInt(b) + 1;
String c = Integer.toString(quantityyp);
mViewHolder.strcount.setText(c);
Utils.qtylist.remove(m);
HashMap<String, String> hashmaplus = new HashMap<String, String>();
hashmaplus.put("categoryId", rem);
hashmaplus.put("quantity", c);
Utils.qtylist.add(hashmaplus);
Log.e("", "#Utils.qtylistadd" + Utils.qtylist);
break;
}
}
}
});
mViewHolder.minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Utils.COUNTCARTALIST.remove(mViewHolder.name.getTag() + "");
int quantityym = 0;
for (int m = 0; m < Utils.qtylist.size(); m++) {
String ii = mViewHolder.minus.getTag() + "";
Log.e("", "#iiminus" + ii);
if (mViewHolder.minus.getTag().equals(Utils.qtylist.get(m).get("categoryId"))) {
rem = Utils.qtylist.get(m).get("categoryId");
b = Utils.qtylist.get(m).get("quantity");
Log.e("", "#QQQ" + b);
Log.e("", "#rem" + rem);
if (b.equals("0")) {
} else {
quantityym = Integer.parseInt(b) - 1;
String c = Integer.toString(quantityym);
mViewHolder.strcount.setText(c);
Utils.qtylist.remove(m);
HashMap<String, String> hashmapminus = new HashMap<String, String>();
hashmapminus.put("categoryId", rem);
hashmapminus.put("quantity", c);
Utils.qtylist.add(hashmapminus);
break;
}
}
}
}
});
return convertView;
}
private class MyViewHolder {
TextView name, prize, strcount, txtproductprize1, txtproductprize2, txtproductprize3;
Button cart, plus, minus, btndropdown, btndropdown1;
ImageView imgbucket;
LinearLayout lnrbelowdry, lnrproduct1, lnrproduct2, lnrproduct3;
CheckBox checkBox1, checkBox2, checkBox3;
public MyViewHolder(View item) {
name = (TextView) item.findViewById(R.id.txtproductname);
prize = (TextView) item.findViewById(R.id.txtprize);
strcount = (TextView) item.findViewById(R.id.txtcount);
imgbucket = (ImageView) item.findViewById(R.id.imgbucket);
plus = (Button) item.findViewById(R.id.btnplus);
minus = (Button) item.findViewById(R.id.btnminus);
btndropdown = (Button) item.findViewById(R.id.btndropdown);
btndropdown1 = (Button) item.findViewById(R.id.btndropdown1);
lnrbelowdry = (LinearLayout) item.findViewById(R.id.lnrbelowdry);
lnrproduct1 = (LinearLayout) item.findViewById(R.id.lnrproduct1);
lnrproduct2 = (LinearLayout) item.findViewById(R.id.lnrproduct2);
lnrproduct3 = (LinearLayout) item.findViewById(R.id.lnrproduct3);
checkBox1 = (CheckBox) item.findViewById(R.id.checkBox1);
checkBox2 = (CheckBox) item.findViewById(R.id.checkBox2);
checkBox3 = (CheckBox) item.findViewById(R.id.checkBox3);
txtproductprize1 = (TextView) item.findViewById(R.id.txtproductprize1);
txtproductprize2 = (TextView) item.findViewById(R.id.txtproductprize2);
txtproductprize3 = (TextView) item.findViewById(R.id.txtproductprize3);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
You are returning a same ID for each row. try this:
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

how to remove the empty cell of custom list-view in my android application

Hi i am doing an application in which i want to show the content depending on the custom and the public ,data is coming from the sever.i am receiving the is_public as a parameter value as 0 and 1 if it is 1 it for public, we need to display to all user if t is 0,we need to display only the custom member like user id 8,10. for rest of the user the received content like user id 11 need to be invisible.
i able to make invisible the content, when i invisible it it is taking blank space in the list view how to remove the blank space i am posting my adapter class below
please help me
public class PlacementsBoardAdapter extends BaseAdapter{
private ArrayList<PlacementsBoardModel> listData;
private LayoutInflater layoutInflater;
ArrayList<PlacementsBoardModel> listData1;
public ImageLoader imageLoader;
DisplayImageOptions profile_options;
ImageView imageview;
private Context prova;
Bitmap bit_map_image;
int isPublic;
String custom;
public PlacementsBoardAdapter(Context context,ArrayList<PlacementsBoardModel> listData){
this.listData = listData;
listData1=listData;
prova = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listData.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
imageLoader =imageLoader.getInstance();
profile_options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.pdfimage)
.showImageForEmptyUri(R.drawable.pdfimage)
.showImageOnFail(R.drawable.pdfimage)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
final ViewHolder holder;
if (layoutInflater == null)
layoutInflater = (LayoutInflater) prova.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null){
convertView = layoutInflater.inflate(R.layout.placementsboardcutomview, null);
holder = new ViewHolder();
/*holder.title_of_placesment = (TextView) convertView.findViewById(R.id.title_of_placesment);
holder.pdf_image_custom=(ImageView)convertView.findViewById(R.id.pdf_image_custom);
holder.created_date = (TextView) convertView.findViewById(R.id.created_date);*/
holder.title_of_placesment = (TextView) convertView.findViewById(R.id.noticetopic);
holder.pdf_image_custom=(ImageView)convertView.findViewById(R.id.notice_title_name_image);
holder.readmore=(TextView)convertView.findViewById(R.id.readmore);
holder.placement_etext = (TextView) convertView.findViewById(R.id.noticetext);
holder.readmorelayout=(RelativeLayout)convertView.findViewById(R.id.bottom_layout);
holder.created_date = (TextView) convertView.findViewById(R.id.createddate);
holder.placementCustomLinear=(LinearLayout)convertView.findViewById(R.id.placementCustomLinear);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
final PlacementsBoardModel placementboardItem = (PlacementsBoardModel) listData.get(position);
holder.title_of_placesment.setText(placementboardItem.getTitle());
holder.created_date.setText(placementboardItem.getCreated_date());
holder.placement_etext.setText(placementboardItem.getDescription());
String description=placementboardItem.getDescription();
isPublic=placementboardItem.getIsPublic();
custom=placementboardItem.getCustom();
if (description!=null&&!placementboardItem.getDownload_file_path().contains("null")) {
holder.placement_etext.setVisibility(View.VISIBLE);
holder.pdf_image_custom.setVisibility(View.VISIBLE);
if(isPublic==0&&Util.USER_ID.contains(custom)){
holder.placementCustomLinear.setVisibility(View.VISIBLE);
}
if (description.length()>350) {
holder.placement_etext.setText(placementboardItem.getDescription().trim().subSequence(0, 300)+"....");
holder.readmorelayout.setVisibility(View.VISIBLE);
}
}
else if(description!=null&&placementboardItem.getDownload_file_path().contains("null")){
if (description.length()>350) {
holder.placement_etext.setText(placementboardItem.getDescription().trim().subSequence(0, 300)+"....");
holder.readmorelayout.setVisibility(View.VISIBLE);
}
else{
holder.readmorelayout.setVisibility(View.GONE);
holder.placement_etext.setVisibility(View.VISIBLE);
holder.pdf_image_custom.setVisibility(View.GONE);
}
}
if(placementboardItem.getDescription().contains("null")&&!placementboardItem.getDownload_file_path().contains("null")) {
holder.placement_etext.setVisibility(View.GONE);
holder.pdf_image_custom.setVisibility(View.VISIBLE);
holder.readmorelayout.setVisibility(View.GONE);
}
//holder.pdf_image_custom.setBackground(background)
if (placementboardItem.getDownload_file_type().contains("jpg")||placementboardItem.getDownload_file_type().contains("jpeg")||placementboardItem.getDownload_file_type().contains("png")) {
Log.i("only jpg or png", "tittle the file for display");
if (placementboardItem.getTitle().length()>=20) {
holder.title_of_placesment.setText(placementboardItem.getTitle().trim().subSequence(0, 20)+"....");
//holder.imageview.setImageBitmap(noticeboardItem.getBit_image());
}else{
//noticeboardItem.getBit_image()
holder.title_of_placesment.setText(placementboardItem.getTitle());
holder.pdf_image_custom.setImageBitmap(bit_map_image);
}
} else {
if (placementboardItem.getTitle().length()>=20) {
holder.title_of_placesment.setText(placementboardItem.getTitle().trim().subSequence(0, 20)+"....");
//holder.imageview.setImageResource(R.drawable.pdfimage);
}else{
holder.title_of_placesment.setText(placementboardItem.getTitle());
//holder.imageview.setImageResource(R.drawable.pdfimage);
Log.i("only pdf", "only pdf");;
}
}
if(isPublic==1&&!Util.USER_ID.contains(custom)){
holder.placementCustomLinear.setVisibility(View.VISIBLE);
}
holder.pdf_image_custom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PlacementsBoardModel notice_data = (PlacementsBoardModel) listData.get(position);
/*String title=notice_data.getTitle();
String description=notice_data.getDescription();
Intent intent = new Intent(prova,DscriptionDisplay.class);
intent.putExtra("title",title);
intent.putExtra("description",description);
prova.startActivity(intent);*/
if (notice_data.getDownload_file_type().contains("jpg")||notice_data.getDownload_file_type().contains("gif")||notice_data.getDownload_file_type().contains("jpeg")||notice_data.getDownload_file_type().contains("png")) {
Log.i("only jpg or png", "tittle the file for display");
Intent intent1 = new Intent(prova,NoticeBoardImageDisplayActivity.class);
intent1.putExtra("noticeimagelink",notice_data.getDownload_file_path());
intent1.putExtra("noticetitle",notice_data.getTitle());
prova.startActivity(intent1);
} else {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(notice_data.getDownload_file_path()));
prova.startActivity(browserIntent);
Log.i("only pdf", "only pdf");
}
notifyDataSetChanged();
}
});
holder.readmore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//placementboardItem = (PlacementsBoardModel) listData.get(position);
String title=placementboardItem.getTitle();
String description=placementboardItem.getDescription();
Intent intent = new Intent(prova,DscriptionDisplay.class);
intent.putExtra("title",title);
intent.putExtra("description",description);
prova.startActivity(intent);
notifyDataSetChanged();
}
});
imageLoader.displayImage(placementboardItem.getDownload_file_path(), holder.pdf_image_custom, profile_options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//bit_map_image=loadedImage;
}
}, new ImageLoadingProgressListener() {
#Override
public void onProgressUpdate(String imageUri, View view, int current,
int total) {
}
}
);
notifyDataSetChanged();
return convertView;
}
static class ViewHolder{
RelativeLayout readmorelayout;
TextView placement_etext;
TextView readmore;
TextView title_of_placesment;
TextView created_date;
ImageView pdf_image_custom;
LinearLayout placementCustomLinear;
}
}
holder.placementCustomLinear is the custom leaner-layout need to be make it invisible
After some research i have solved my problem by adding a parent layout in the the xml and adding the some logic in the adapter class like
if (Util.ROLE.equalsIgnoreCase("admin")) {
holder.placementCustomLinear.setVisibility(View.VISIBLE);
}else
if(isPublic==0){
Log.i("inside if ", ""+isPublic);
Log.i("custom disply", custom);
int[] arry= stringToInteger(custom);
Log.i("numbers to ccheck ", ""+(arry));
for (int i = 0; i < arry.length; i++) {
if(custom.contains(Util.USER_ID)){
Log.i("true checked ", "inside");
holder.placementCustomLinear.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}else{
holder.placementCustomLinear.setVisibility(View.GONE);
notifyDataSetChanged();
}
}
if(isPublic==0&&Util.USER_ID.contains(custom)){
holder.placementCustomLinear.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
}
else{
Log.i("else block ",""+isPublic);
if(isPublic==1)
holder.placementCustomLinear.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
my problem is solved thanks for the people who have give some suggestion

Custom BaseAdapter wont add new Data - Android

I have a custom baseadapter that creates comment boxes. Everything works great on it until I want to add data. When I try to add the data it deletes the previous data and adds the new data. How do I make it so it keeps all the data? Is my Add method incorrect? Here is my baseadapter,
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
public int getCount1() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
public Object getItem1(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
public long getItemId1(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView1(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}
Setting the adapter:
final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);
lstComments = (ListView)findViewById(android.R.id.list);
lstComments.setAdapter(mycmlist);
This is what how I call the add method,
mycmlist.add(comments,usernames,numbers);
mycmlist.notifyDataSetChanged();
In your add method you're setting the arrays to new values listComments = comments; That's replacing your old data with the new data.
You could use System.arrayCopy() to resize your listArrays to the new size and append the new items. A much less tedious approach, however, would be to store your arrays as List<String>, allowing you to add more items without worrying about resizing lists.
The result would look something like this...
public class CommentsAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private List<String> comments;
private List<String> numbers;
private List<String> usernames;
public CommentsAdapter(Context context)
{
inflater = LayoutInflater.from(context);
comments = new ArrayList<String>();
numbers = new ArrayList<String>();
usernames = new ArrayList<String>();
}
public void add(String[] comments, String[] numbers, String[] usernames)
{
this.comments.addAll(Arrays.asList(comments));
this.numbers.addAll(Arrays.asList(numbers));
this.usernames.addAll(Arrays.asList(usernames));
notifyDataSetChanged();
}
#Override
public int getCount()
{
if (comments == null)
return 0;
return comments.size();
}
#Override
public String getItem(int position)
{
return comments.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = inflater.inflate(R.layout.list_item, parent, false);
convertView.setTag(new ViewHolder(convertView));
}
ViewHolder holder = (ViewHolder) convertView.getTag();
holder.commentView.setText(comments.get(position));
//Other view bind logic here...
return convertView;
}
private static class ViewHolder
{
public TextView commentView;
public TextView numbersView;
public TextView usernamesView;
public Button usernameButton;
public Button numberButton;
public ViewHolder(View v)
{
commentView = (TextView) v.findViewById(R.id.listComment);
numbersView = (TextView) v.findViewById(R.id.listNumber);
usernamesView = (TextView) v.findViewById(R.id.listPostedBy);
usernameButton = (Button) v.findViewById(R.id.listUsernameButton);
numberButton = (Button) v.findViewById(R.id.listNumberButton);
}
}
}
I also highly recommend reading this page on the Android Developer's site: http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Your current adapter implementation is very inefficient, and that page should help you iron out some kinks.
You probably need to add the String[] array to the existing one, instead of replacing it.
Add this function which joins two arrays (Sadly there is no already-implemented method for Java):
String[] concat(String[] A, String[] B) {
String[] C= new String[A.length + B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}
Credits: Sun Forum
And then change the add method to this:
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = concat(listComments, comments);
listUsernames = concat(listUsernames, usernames);
listNumbers = concat(listNumbers, numbers);
}
And you had a typo in your code. In the add method, the listUsernames and listNumbers should be swapped I think.. I fixed it for you.

Categories

Resources