does anyone know how to color the background of each row in a listview as they are created?
I have an arraylist which is pulled from my database and populates a layout with a listview in it.
I suspect there might be a way to do it with a simpleadaptor but cant figure it out.
Any help would be much appreciated :)
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.item_list);
// Read var from Intent
Intent intent= getIntent();
final String ListID = intent.getStringExtra("ListID");
golbalItemID = ListID;
ivAdd = (ImageView) findViewById(R.id.ivAdd);
ivCancel = (ImageView) findViewById(R.id.ivCancel);
tvTotItems = (TextView) findViewById(R.id.tvTotItems);
final myDBClass myDb = new myDBClass(this);
final ArrayList<HashMap<String, String>> MebmerList = myDb.SelectAllItemData(ListID);
myData = myDb.SelectItemData(Integer.parseInt(ListID.toString()));
// listView1
final ListView lisView1 = (ListView)findViewById(R.id.listView1);
registerForContextMenu(lisView1);
MyAdapter sAdap;
sAdap = new MyAdapter(ListItems.this, MebmerList, R.layout.activity_column, new String[] {"Name", "Price", "Quan"}, new int[] {R.id.ColName, R.id.ColTel, R.id.ColQuan});
lisView1.setAdapter(sAdap);
lisView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int position, long mylng) {
int iChk = 0;
// Show Data
String arrData[] = myDb.SelectItemData((MebmerList.get(position).get("ItemID").toString()));
if(arrData != null)
{
iChk = Integer.parseInt(arrData[4]);
}
if(iChk == 1)
{
ischkCheck(Integer.parseInt(MebmerList.get(position).get("ItemID").toString()), 0);
change_color(lisView1, position, 255, 255, 255);
System.out.println("POSITION!ichk=1" + myAdapter.getItemAtPosition(position).toString());
setTitle(myAdapter.getItemAtPosition(position).toString());
}
else if(iChk == 0)
{
ischkCheck(Integer.parseInt(MebmerList.get(position).get("ItemID").toString()), 1);
change_color(lisView1, position, 155, 155, 138);
System.out.println("POSITION!ichk=0" + myAdapter.getItemAtPosition(position).toString());
}
}});
ivAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent newActivity = new Intent(ListItems.this,AddItem.class);
newActivity.putExtra("ListID", ListID);
startActivity(newActivity);
finish();
}
});
ivCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent newActivity = new Intent(ListItems.this,MenuScreen.class);
startActivity(newActivity);
finish();
}
});
Create an Adapter Class, and control each Row's color in it, then set it as adapter of ListView
Here is a sample code from one of my projects, check getView function:
public class ListAdapter extends BaseAdapter {
private LayoutInflater myInflater;
private List<Poet> list;
public ListAdapter(Context context) {
super();
myInflater = LayoutInflater.from(context);
Log.d("Ganjoor", "Data passed to the adapter.");
}
static class ViewHolder {
TextView tvName;
}
public void setData(List<Poet> list) {
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Poet getItem(int position) {
return (null == list) ? null : list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = myInflater.inflate(R.layout.list_adapter, parent,
false);
holder = new ViewHolder();
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setTag(list.get(position).getId());
holder.tvName.setText(list.get(position).getName());
// Log.d("Ganjoor", "Adapter: " + list.get(position).getName());
if (position % 2 == 0) {
convertView.setBackgroundResource(R.drawable.grad_blue);
} else {
convertView.setBackgroundResource(R.drawable.row_style);
}
return convertView;
}
}
As #Nikita Beloglazov states, you can do this by implementing a custom ArrayAdapter, putting your coloring scheme in the getView Override method. See ArrayAdapter doc.
Related
I am having a listview and it has one checkbox and two textfields , i would like to change check box visibility properties from listview on click funtion, i am able to change the properties from inside the getView funtion but i want it from listview click. Help me find a solution
public class HelpList extends Fragment {
amfFunctions amf;
MyCustomAdapter dataAdapter = null;
Database_Contact contact = new Database_Contact();
DBHelper mydb = new DBHelper(getActivity());
public static final int PICK_CONTACT = 1;
public String user_phone_number;
public String buddyName;
public String buddyNum;
LayoutInflater vi;
View v ;
Fragment fragment = null;
Button myAddButton,myDelButton;
int selected = 0;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayList<Database_Contact> selectedList = new ArrayList<>();
Database_Contact addcontacts = new Database_Contact();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.activity_helplist, container, false);
// Inflate the layout for this fragment
displayListView();
cd = new ConnectionDetector(getActivity());
myDelButton = (Button)v. findViewById(R.id.deleteContact);
myDelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
DeleteContact();
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_SHORT).show();
}
}
});
Constants.i = 0;
myAddButton = (Button)v. findViewById(R.id.Addanother);
myAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
Log.e("Myaddbutton text ", (String) myAddButton.getText());
if (isInternetPresent) {
if (myAddButton.getText().equals("Close")){
Toast.makeText(getActivity(),
getString(R.string.click_to_close), Toast.LENGTH_SHORT).show();
}
else{
AddContact();
}
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_LONG).show();
}
}
});
return v;
}
private void displayListView() {
mydb = new DBHelper(getActivity());
ArrayList<Database_Contact> contactlist = (ArrayList<Database_Contact>)
mydb.getAllDatabase_Contacts();
Collections.sort(contactlist, new Comparator<Database_Contact>() {
#Override
public int compare(Database_Contact lhs, Database_Contact rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.activity_allcontactlist, contactlist);
ListView listView = (ListView)v.findViewById(R.id.helplistview);
// Assign adapter to ListView
listView.setTextFilterEnabled(true);
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact)
parent.getItemAtPosition(position);
contact.isSelected();
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Database_Contact> {
private ArrayList<Database_Contact> contactlist;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Database_Contact> contactlist) {
super(context, textViewResourceId, contactlist);
this.contactlist = new ArrayList<Database_Contact>();
this.contactlist.addAll(contactlist);
}
private class ViewHolder {
TextView code;
TextView Number;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.activity_allcontactlist,
null);
holder = new ViewHolder();
holder.code = (TextView)
convertView.findViewById(R.id.helplist_name);
holder.Number = (TextView)
convertView.findViewById(R.id.helplist_num);
holder.name = (CheckBox)
convertView.findViewById(R.id.checkbox_all);
convertView.setTag(holder);
final ViewHolder finalHolder = holder;
final ViewHolder finalHolder1 = holder;
holder.code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.Number.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Database_Contact contact = (Database_Contact)
cb.getTag();
contact.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Database_Contact contact = contactlist.get(position);
holder.code.setText(contact.getName());
holder.Number.setText(contact.getPhoneNumber());
holder.name.setText("");
holder.name.setChecked(contact.isSelected());
holder.name.setTag(contact);
return convertView;
}
}
}
As I could not find any perfect solution i tried it in a different manner alough its a bit diffenrt from what i wanted i.e on click i used my displayListView() funtion and got the work done
ischeckboxVisible = true;
Runnable run = new Runnable() {
#Override
public void run() {
displayListView();
}
};
getActivity().runOnUiThread(run);
and coming to getView i have used:
if (!ischeckboxVisible)
{
holder.name.setVisibility(View.GONE);
}
if (ischeckboxVisible)
{
holder.name.setVisibility(View.VISIBLE);
}
so every time i do the click it changes the ischeckboxVisible to either true or false and initializes the displatListview() and it works.
I have had help from here Android hide and show checkboxes in custome listview on button click
Hope this might come in handy for some one out there.
Please check below code if it helps you,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact) contactlist.get(position);
contact.setSelected(!contact.isSelected());
if(contact.isSelected())
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.VISIBLE);
}
else
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.GONE);
}
}
});
Its been a week since I'm stuck with this problem.
I developed an application with a listView and editText to make a search. When I make a search the new list is showed very well but when I click on the item it redirect me to the item of the inicial list.
I don't know what to do please help me. These are my codes.
-For the ReaderListAdapter :
public class ReaderListAdapter extends BaseAdapter {
ArrayList<Reader> listReader = new ArrayList<Reader>();
ArrayList<Reader> arrayList;
LayoutInflater layoutInflater;
Context context;
int lastPosition = -1;
// constructeur
public ReaderListAdapter(Context context, ArrayList<Reader> listReader) {
this.listReader = listReader;
this.context = context;
arrayList = new ArrayList<Reader> ();;
layoutInflater = LayoutInflater.from(this.context);
arrayList.addAll(listReader);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listReader.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listReader.get(position);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
static class ViewHolder {
TextView nomView;
TextView priceView;
ImageView pictureView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.reader_row, null);
holder = new ViewHolder();
// initialisation des vues
holder.nomView = (TextView) convertView.findViewById(R.id.name);
holder.priceView = (TextView) convertView.findViewById(R.id.price);
holder.pictureView = (ImageView) convertView.findViewById(R.id.picture);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// affchier les données convenablement dans leurs positions
holder.nomView.setText(listReader.get(position).getName());
holder.priceView.setText(String.valueOf(listReader.get(position).getPrice()));
holder.pictureView.setBackgroundDrawable(listReader.get(position).getPicture());
// changer R.anim.ton_effet
Animation animation = AnimationUtils.loadAnimation(context,(position > lastPosition)
? R.anim.up_from_bottom: R.anim.up_from_bottom);
convertView.startAnimation(animation);
position=lastPosition;
return convertView;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
listReader.clear();
if(charText.length()==0){
listReader.addAll(arrayList);
}
else{
for (Reader c : arrayList) {
if (c.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
listReader.add(c);
}
}
}
notifyDataSetChanged();
}
}
-For the MainActivity:
public class MainActivity extends Activity {
String[] listNames = { "kooora","yahoo", "hespress"};
int[] listPrices = { 1, 2, 3 };
ArrayList<Reader> listReader = new ArrayList<Reader>();;
ArrayList<Reader> listReaderNew;
ListView lv;
EditText search;
ReaderListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listReader);
search = (EditText) findViewById(R.id.search);
Drawable[] listPictures = {getResources().getDrawable(R.drawable.a1),getResources().getDrawable(R.drawable.a2),getResources().getDrawable(R.drawable.a3)};
for (int i = 0; i < listPictures.length; i++) {
listReader.add(new Reader(i + 1, listNames[i], listPictures[i], listPrices[i]));
}
adapter=new ReaderListAdapter(getApplicationContext(), listReader);
lv.setAdapter(adapter);
//lv.setAdapter(new ReaderListAdapter(getApplicationContext(), listReader));
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault());
MainActivity.this.adapter.filter(text);
}});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent=new Intent(MainActivity.this,WebActivity.class);
switch (position) {
case 0:
intent.setData(Uri.parse("http://www.kooora.com")) ;break;
case 1:
intent.setData(Uri.parse("http://www.yahoo.com")) ;break;
case 2:
intent.setData(Uri.parse("http://www.hespress.com")) ;break; }if (intent != null) {
startActivity(intent);
}}});}}
Please help me. Thanks in advance!
I think the code in onItemClick is causing this.
The problem:
searchTerm = "yahoo"
You filter yahoo and show the listitem for yahoo. Lets says its position in the list is 0. When the user clicks it, the onItemClick will be called and case 0: will be executed.
The correct logic should be,
Reader reader = parent.getAdapter().getItem(position);
String searchTerm = reader.getName(); // or whichever is the id for that listitem
if(searchTerm.contains("yahoo")) {
intent.setData(Uri.parse("http://www.yahoo.com"))
} // and so on
My problem is that when I am clicking on radio button it will change the spinner value randomly at any position..please help here is my adapter class..
public class ManageAdapter extends BaseAdapter {
ArrayList<String> _manageArrayList = null;
private Context _Context = null;
private Integer selectedPosition = 0;
String List1[]=new String[]{"In use","Lost" ,"Stolen" , "For sale"};
private int flag = 0;
public ManageAdapter(ArrayList<String> _manageArrayList, Context _Context) {
super();
this._manageArrayList = _manageArrayList;
this._Context = _Context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return _manageArrayList != null? _manageArrayList.size():0;
}
#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 0;
}
public static class ViewHolder
{
public TextView itemTextView;
public RadioButton myitemButton;
public Spinner inUseSpinner;
public RelativeLayout managelayout;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater)_Context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(v == null)
{
holder = new ViewHolder();
v = inflater.inflate(R.layout.manage_single_row, null,false);
holder.managelayout = (RelativeLayout)v.findViewById(R.id.single_row_layout);
holder.itemTextView = (TextView)v.findViewById(R.id.item_name_txt);
holder.myitemButton = (RadioButton)v.findViewById(R.id.manage_radio_buton);
holder.inUseSpinner = (Spinner)v.findViewById(R.id.Status_spinner);
v.setTag(holder);
ArrayAdapter<String> Adapter = new ArrayAdapter<String>(_Context,R.layout.spinner_color,List1);
Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
holder.inUseSpinner.setAdapter(Adapter);
}else {
holder = (ViewHolder) v.getTag();
}
holder.itemTextView.setText(_manageArrayList.get(position));
holder.inUseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// int getPosition = (Integer) arg0.getTag();
// Toast.makeText(_Context,List1[position] ,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
if(flag == 0)
{
flag = 1;
holder.myitemButton.setChecked(false);
holder.myitemButton.setTag(position);
}else {
holder.myitemButton.setChecked(position == selectedPosition);
holder.myitemButton.setTag(position);
}
holder.myitemButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer)v.getTag();
notifyDataSetInvalidated();
}
});
return v;
}
}
Thanks in advance
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_item);
_backButton = (Button)findViewById(R.id.back);
_backButton.setOnClickListener(this);
_headerTextView = (TextView)findViewById(R.id.header_TextView);
_headerTextView.setText("My Items");
_uploadButton = (ImageButton)findViewById(R.id.Upload_file_button);
_uploadButton.setOnClickListener(this);
_addmanullyButton = (ImageButton)findViewById(R.id.add_item_manually);
_addmanullyButton.setOnClickListener(this);
_addphoneButton = (ImageButton)findViewById(R.id.auto_add_phone);
_addphoneButton.setOnClickListener(this);
_modifyButton = (ImageButton)findViewById(R.id.modify_button);
_modifyButton.setOnClickListener(this);
_transferButton = (ImageButton)findViewById(R.id.transfer_ownership);
_transferButton.setOnClickListener(this);
_hideenButton = (Button)findViewById(R.id.hideen_button);
_hideenButton.setOnClickListener(this);
_manageListView = (ListView)findViewById(R.id.manage_listview);
prepareList();
_adapter = new ManageAdapter(listItem, this);
_manageListView.setAdapter(_adapter);
}
public void prepareList() {
listItem = new ArrayList<String>();
listItem.add("Android smart");
listItem.add("sony");
listItem.add("samsung");
listItem.add("micromax");
listItem.add("tablet");
}
#Override
public void onClick(View view) {
Intent intent = null;
switch (view.getId()) {
case R.id.Upload_file_button:
intent = new Intent(ManageItems.this, UploadFileActivity.class);
startActivity(intent);
break;
case R.id.modify_button:
intent = new Intent(ManageItems.this, ModifyActivity.class);
startActivity(intent);
break;
case R.id.transfer_ownership:
intent = new Intent(ManageItems.this, TransferOwnerShip.class);
startActivity(intent);
break;
case R.id.add_item_manually:
intent = new Intent(ManageItems.this, AddManuallyActivity.class);
startActivity(intent);
break;
case R.id.auto_add_phone:
intent = new Intent(ManageItems.this, AutoAddActivity.class);
startActivity(intent);
break;
case R.id.back:
intent = new Intent(ManageItems.this, MenuActivtiy.class);
startActivity(intent);
break;
case R.id.hideen_button:
intent = new Intent(ManageItems.this, MenuActivtiy.class);
startActivity(intent);
break;
}
Thanks all but I got the solution of my question..
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
MyItemListDataHolder myItemListDataHolder = _manageArrayList.get(position);
LayoutInflater inflater = (LayoutInflater)_Context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(v == null)
{
holder = new ViewHolder();
v = inflater.inflate(R.layout.manage_single_row, null,false);
holder.managelayout = (RelativeLayout)v.findViewById(R.id.single_row_layout);
holder.itemTextView = (TextView)v.findViewById(R.id.item_name_txt);
holder.myitemButton = (RadioButton)v.findViewById(R.id.manage_radio_buton);
holder.inUseSpinner = (Spinner)v.findViewById(R.id.Status_spinner);
v.setTag(holder);
}else {
holder = (ViewHolder) v.getTag();
}
holder.itemTextView.setText(myItemListDataHolder.get_itemName());
Adapter = new ArrayAdapter<String>(_Context,R.layout.spinner_color,List1);
Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
holder.inUseSpinner.setAdapter(Adapter);
if(myItemListDataHolder.get_selectedItem() > 0){
holder.inUseSpinner.setSelection(myItemListDataHolder.get_selectedItem());
}else{
holder.inUseSpinner.setSelection(0);
}
holder.inUseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
private Intent intent;
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position1, long arg3) {
_manageArrayList.get(position).set_selectedItem(position1);
// notifyDataSetChanged();
String status=holder.inUseSpinner.getSelectedItem().toString();
if(status.equalsIgnoreCase("Lost"))
{
intent = new Intent (_Context, LostItemActivity.class);
startActivity(intent);
}else if (status.equalsIgnoreCase("Stolen")) {
intent = new Intent (_Context, StolenItemActivity.class);
startActivity(intent);
}else if (status.equalsIgnoreCase("Stolen")) {
intent = new Intent (_Context, LostFoundActivity.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
if(flag == 0)
{
flag = 1;
holder.myitemButton.setChecked(false);
}else {
holder.myitemButton.setChecked(position == selectedPosition);
}
holder.myitemButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = position;
notifyDataSetChanged();
//_adapter.notifyDataSetChanged();
}
});
return v;
}
}
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.
My ListView consist an ImageView and a TextView I need to get the Text from the TextView.
int the position of my list where I press (onItemClick).
How can I do that?
The 1 class have a Button then when you press I moving to the next activity (CountryView)
and expect to get back from the next activity with a text (name of the selected Country)
The 2 classes have a ListView (ImageView and TextView) the data is getting from a database and showing on the ListView.
My problem is to get back to the 1 class the selected name of the country.
Thanks so much for helping!!!
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// final int recquestCode = 0;
final Button btnCountry = (Button) findViewById(R.id.fromButton);
btnCountry.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent pingIntent = new Intent("CountryView");
pingIntent.putExtra("btnText", " ");
pingIntent.setClass(Travel.this, CountryView.class);
startActivityForResult(pingIntent, RECEIVE_MESSAGE);
}
});
/* Button btnSearch = (Button) findViewById(R.id.searchButton);
btnSearch.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(v.getContext(), ResultView.class);
startActivityForResult(intent, 0);
}
});*/
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (data.hasExtra("response")){
Button b = (Button)findViewById(R.id.fromButton);
CharSequence seq = data.getCharSequenceExtra("response");
b.setText(seq);
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.country);
mListUsers = getCountry();
lvUsers = (ListView) findViewById(R.id.countrylistView);
lvUsers.setAdapter(new ListAdapter(this, R.id.countrylistView, mListUsers));
// lvUsers.setTextFilterEnabled(true);
// String extraMsg1 = getIntent().getExtras().getString("extra1");
lvUsers.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// When clicked, show a toast with the TextView text
//textItem=view;
// Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
// Toast.LENGTH_SHORT).show();
Intent pongIntent = new Intent();
// lvUsers.getItemAtPosition(position);
t = (TextView) view;
Log.v("fffvd"+t, null);
t.setText(getIntent().getStringExtra("btnText"));
String strText = t.getText().toString();
//((TextView) view).getText().toString()
pongIntent.putExtra("response",strText);
setResult(Activity.RESULT_OK,pongIntent);
finish();
// startActivity(new Intent(CountryView.this,TravelPharmacy.class));
}
});
}
public ArrayList<Country> getCountry(){
DBHelper dbAdapter=DBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM Pays;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<Country> countryList = new ArrayList<Country>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
Country country = new Country();
try {
//country.id = Integer.parseInt(list.get(0));
country.pays = list.get(1);
// country.age = Long.parseLong(list.get(2));
} catch (Exception e) {
Log.i("***" + TravelPharmacy.class.toString(), e.getMessage());
}
countryList.add(country);
}
return countryList;
}
#Override
public void onDestroy()
{
// adapter.imageLoader.stopThread();
lv.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// adapter.imageLoader.clearCache();
((BaseAdapter) adapter).notifyDataSetChanged();
}
};
CountryAdapter Class
public class CountryAdapter extends BaseAdapter {
private Activity activity;
private String[] data;
private LayoutInflater inflater=null;
// public ImageLoader imageLoader;
public CountryAdapter(Activity a, String[] d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class ViewHolder
{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.singlecountry, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);;
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("item "+data[position]);
holder.image.setTag(data[position]);
return vi;
}
}
ListAdapter Class
private class ListAdapter extends ArrayAdapter<Country> { // --CloneChangeRequired
private ArrayList<Country> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<Country> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.singlecountry, null); // --CloneChangeRequired(list_item)
}
final Country listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting singleCountry views
// ( (TextView) view.findViewById(R.id.tv_id) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.text) ).setText( listItem.getPays() );
//((ImageView)view.findViewById(R.id.image)).setImageDrawable(drawable.world);
//( (TextView) view.findViewById(R.id.tv_age) ).setText( listItem.getAge()+"" );
}}catch(Exception e){
Log.i(CountryView.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}
When you add things to the list, you can add hashmaps to the arraylist which the adapter looks at. Then you can grab the values which are name value pairs.
I think you want to get the position of the list you clicked, Its simple you can use OnItemClickListener as follows
YourList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position=arg2;
// where position is the clicked position
} }
If you stored your data in String array pass this position say array[position] to string array you can get the Text..