Changing TextView color in different xml files - android

I have a ListView in one xml referencing a TextView in another xml. I'm trying to change the color of the TextView but this doesn't seem to work. If I don't set the 'setContentView' twice I got a NullPointerException.
setContentView(R.layout.text_list);
TextView textView = (TextView) findViewById(R.id.logText);
if (logLevel == "E"){
textView.setTextColor(Color.parseColor("#FF4D4D"));
}
else if (logLevel == "W"){
textView.setTextColor(Color.parseColor("#EAAB55"));
}
else if (logLevel == "I"){
textView.setTextColor(Color.parseColor("#AFD778"));
}
else if (logLevel == "V"){
textView.setTextColor(Color.parseColor("#OOOOOO"));
}
else {
textView.setTextColor(Color.parseColor("#AFD778"));
}
setContentView(R.layout.log_cat);
ListView lv1 = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this, R.layout.text_list, log);

// setContentView(parm ) for twice may cause problem. So If there need view from different layout then simply inflate them
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.log_cat);
ListView lv1 = (ListView) findViewById(R.id.listView1);
CustomAdapter adapter = new CustomAdapter(this, "V");
lv1 .setAdapter(adapter);
adapter.notifyDataSetChanged();
}
// custom adapter
public class CustomAdapter extends BaseAdapter {
private Context ctx;
private String logLevel;
CustomAdapter (ArrayList<String> data, Context context, String log)
{
this.ctx = context;
this.logLevel = log;
}
#Override
public int getCount()
{
list.size();
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position)
{
return position ;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflator = (LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.text_list, null);
TextView textView = (TextView) v.findViewById(R.id.logText);
if (logLevel == "E"){
textView.setTextColor(Color.parseColor("#FF4D4D"));
}
else if (logLevel == "W"){
textView.setTextColor(Color.parseColor("#EAAB55"));
}
else if (logLevel == "I"){
textView.setTextColor(Color.parseColor("#AFD778"));
}
else if (logLevel == "V"){
textView.setTextColor(Color.parseColor("#OOOOOO"));
}
else {
textView.setTextColor(Color.parseColor("#AFD778"));
textView.setTextColor(Color.BLUE);
}
return textView;
}
}

Related

Android extends listview inside scrollview depends on the number of value

I created an app composed of listview of teachers wherein the data is in sqlite. When i click one of the listview, the profile of teacher will appear and there's a list of students inside of it. BTW the profile of teacher has a scroll since it has many info. I apply the top answer here so the listview will automatically extends depends on the number of students of the teacher. But i got error when i apply this. I'll post the error and my code below.
public class MainActivity extends AppCompatActivity {
Button btnback, btnnext, btnbackprofile;
TextView profileteacher;
List<TeacherModel> GetAllTeacher;
List<StudentModel> GetTeacherStudent;
Context context = this;
DatabaseHelper dbhelper;
DatabaseHelper db = new DatabaseHelper(this);
ListView lv,lv2;
View TeacherListView,TeacherProfileView;
int index = 0;
private int currentPageIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbhelper = new DatabaseHelper(MainActivity.this);
try{
dbhelper.createDataBase();
}
catch(IOException e){
e.printStackTrace();
}
try {
dbhelper.openDataBase();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Till here
GetAllTeacher = dbhelper.getAllTeacher(index);
lv = (ListView) findViewById(R.id.teacher_list);
lv.setAdapter(new ViewAdapter());
/****************************************************************************************
* TEACHER PROFILE
****************************************************************************************/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,final int i, long l) {
GetTeacherStudent = dbhelper.getTeacherStudent(GetAllTeacher.get(i).getid());
TeacherListView = findViewById(R.id.teacherlayout);
ViewGroup parent = (ViewGroup) TeacherListView.getParent();
parent.removeView(TeacherListView);
// inflate your profile view (or get the reference to it if it's already inflated)
TeacherProfileView = getLayoutInflater().inflate(R.layout.profile_teacher, parent, false);
// add it to the parent
parent.addView(TeacherProfileView);
ListView listView = (ListView)view.findViewById(R.id.profileStudentList);
setListViewHeightBasedOnChildren(listView);
listView.setAdapter(new ViewAdapter2());
btnbackprofile = (Button) findViewById(R.id.profileTeacherBack);
btnbackprofile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TeacherProfileView != null && TeacherProfileView.getParent() != null) {
// remove your profile view
ViewGroup parent = (ViewGroup) TeacherProfileView.getParent();
parent.removeView(TeacherProfileView);
// a reference to yourListView has to be saved somewhere; just get it
// add your listview to the parent
parent.addView(TeacherListView);
} else {
}
}
});
profileteacher = (TextView) findViewById(R.id.profileTeacherName);
profileteacher.setText(GetAllTeacher.get(i).getname());
}
});
btnback = (Button) findViewById(R.id.teacherBack);
btnnext = (Button) findViewById(R.id.teacherNext);
btnback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View convertView) {
currentPageIndex -= 20;
GetAllTeacher = dbhelper.getAllTeacher(currentPageIndex);
lv = (ListView) findViewById(R.id.teacher_list);
lv.setAdapter(new ViewAdapter());
}
});
btnnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View convertView) {
currentPageIndex += 20;
GetAllTeacher = dbhelper.getAllTeacher(currentPageIndex);
lv = (ListView) findViewById(R.id.teacher_list);
lv.setAdapter(new ViewAdapter());
}
});
}
/****************************************************************************************
* CODE IN THE LINK THAT I APPLY
****************************************************************************************/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, AbsListView.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
/****************************************************************************************
* CUSTOM LIST
****************************************************************************************/
public class ViewAdapter extends BaseAdapter {
LayoutInflater mInflater;
public ViewAdapter() {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return GetAllTeacher.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_teacher,null);
}
final TextView names = (TextView) convertView.findViewById(R.id.teacherlist_name);
final TextView gender = (TextView) convertView.findViewById(R.id.teacherlist_gender);
names.setText("Dr. "+GetAllTeacher.get(position).getname());
gender.setText(GetAllTeacher.get(position).getgender());
return convertView;
}
}
public class ViewAdapter2 extends BaseAdapter {
LayoutInflater mInflater;
public ViewAdapter2() {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return GetTeacherStudent.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_teacherstudent,null);
}
final TextView names = (TextView) convertView.findViewById(R.id.teacherlist_name);
names.setText(GetTeacherStudent.get(position).getstudent());
return convertView;
}
}
}
Error
Attempt to invoke virtual method 'android.widget.ListAdapter
android.widget.ListView.getAdapter()' on a null object reference at
com.example.jathniel.studentlist.MainActivity.setListViewHeightBasedOnChildren(MainActivity.java:243)
at
com.example.jathniel.studentlist.MainActivity$1.onItemClick(MainActivity.java:100)
Line 243: ListAdapter listAdapter = listView.getAdapter();
Line 100: setListViewHeightBasedOnChildren(listView);
why you are entering the list view in setListViewHeightBasedOnChildren change it into like this setListViewHeightBasedOnChildren() and declare this in the oncreate() ListView listView = (ListView)view.findViewById(R.id.profileStudentList);
then try
edit
in you method change it to like this :
public static void setListViewHeightBasedOnChildren() {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
and on oncreate() method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbhelper = new DatabaseHelper(MainActivity.this);
listView = (ListView)findViewById(R.id.profileStudentList);
Interchange your line 100 and 101.
As line 101 setting adapter to listView.
And line 100 try to get adapter from listView.
But at the time of line 100 there will be no adapter set to list view. So it will throw null pointer exception.
So code will be like this
listView.setAdapter(new ViewAdapter2());
setListViewHeightBasedOnChildren(listView);

add a row in custom ListView and get the data from intent.putExtra()

I have a custom listView that is empty in first time , from other side i have an activity which contains a product details such as picture, title, model .in this activity there is a button , so when user press this button i want to add the product into my custom listView and shows all the product details there,
my listView is:
public class ListViewShoppingBasketActivity extends Activity {
BaseAdapter adapter;
ArrayList<SingleRow> list;
Context context;
String[] titles;
Bitmap[] images;
String[] descriptions;
TextView title;
TextView description;
ImageView image;
String rowTitles;
String rowDescription;
Bitmap rowImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_shopping_basket_layout);
final ListView list = (ListView) findViewById(R.id.listView1);
list.setAdapter(new MyAdapter(this));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
if (id == 0) {
} else if (id == 1) {
} else if (id == 2) {
} else if (id == 3) {
} else if (id == 4) {
}
}
});
}
class SingleRow {
String rowTitles;
String rowDescription;
Bitmap rowImage;
public SingleRow(String rowTitles, String rowDescription, Bitmap rowImage) {
this.rowTitles = rowTitles;
this.rowDescription = rowDescription;
this.rowImage = rowImage;
}
}
class MyAdapter extends BaseAdapter {
public MyAdapter(Context c) {
context = c;
list = new ArrayList<SingleRow>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.shopping_basket_listview_row,
viewGroup, false);
title = (TextView) row.findViewById(R.id.textView1);
description = (TextView) row.findViewById(R.id.textView2);
image = (ImageView) row.findViewById(R.id.imageView1);
SingleRow temp = list.get(i);
title.setText(temp.rowTitles);
description.setText(temp.rowDescription);
image.setImageBitmap(temp.rowImage);
return row;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.list_view_shopping_basket, menu);
return true;
}
// // **********baraye add kardane item jadid be listview
public void addItems(View v) {
list.add(new SingleRow(rowTitles, rowDescription, rowImage));
adapter.notifyDataSetChanged();
}
}
and this is implementation of my button in other activity
b_add_to_cart = (Button) findViewById(R.id.b_add_to_cart);
b_add_to_cart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BarcodeDetailsActivity.this,
ListViewShoppingBasketActivity.class);
intent.putExtra("productID", proId);
intent.putExtra("productModel", proModel);
intent.putExtra("productTitle", proTitle);
intent.putExtra("productPictureUrl", mIcon11);
startActivity(intent);
}
});
my problem is , i dont know how and where i can assign my product details in my listview
You can put the next lines to the code of the ListViewShoppingBasketActivity:
Intent i = getIntent();
if (i.getExtras() != null){
int prodId = i.getExtras().getInt("productID");
....
}
You can put theese to an ArrayList, and use an BaseAdapter (http://developer.android.com/reference/android/widget/BaseAdapter.html) to display the data in the list.

Why do I have to scroll to refresh my list view?

I'm new to android. I'm trying to get my list view to update, I've tried everything...from calling notifydatasetchanged on the ui thread to just simply recreating my list adapter but for whatever reason when I update, no matter which method I use I have to scroll to see the changes. By this I mean that the data updates (say 13:01 changes to 13:02 in the list), it will update, but to see the change I have to scroll so that 13:01 goes off screen and then move back and it will have updated visually.
Why is this? (I can't post code right now as I'm on my phone but if required I will post later.)
EDIT: Here's the relevant code...sorry it took so long I haven't been at my computer for a couple of days.
Relevant parts of ListFragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.match_fragment, container, false);
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MatchAdapter adapter = (MatchAdapter) this.getListAdapter();
if(futureMatches)
adapter = new MatchAdapter (this.getActivity(), ((MainActivity)this.getActivity()).getMatches(), futureMatches);
else
adapter = new MatchAdapter (this.getActivity(), ((MainActivity)this.getActivity()).getPastMatches(), futureMatches);
setListAdapter(adapter);
}
public void refresh()
{
MatchAdapter adapter;
//Update array in mainactivity
if(futureMatches)
MainActivity.refreshMatches((MainActivity) getActivity());
else
MainActivity.refreshPastMatches((MainActivity) getActivity());
//put updated entries in the adapter
if(futureMatches)
adapter = new MatchAdapter (getActivity(), ((MainActivity)getActivity()).getMatches(), futureMatches);
else
adapter = new MatchAdapter (getActivity(), ((MainActivity)getActivity()).getPastMatches(), futureMatches);
setListAdapter(adapter);
updateList();
}
public void updateList(){
this.getActivity().runOnUiThread(new Runnable() {
public void run() {
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
getListView().refreshDrawableState();
getListView().invalidate();
}
});
}
public void onViewStateRestored(Bundle savedInstanceState)
{
super.onViewStateRestored(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
refresh();
}
My adapter class:
public class MatchAdapter extends BaseAdapter
{
private final Activity context;
private LayoutInflater inflater;
private boolean time = false;
private boolean futureMatchAdapter = true;
private ArrayList<String> matchList;
public MatchAdapter(Context cont, ArrayList<String> matches, boolean isFutureMatchAdapter)
{
matchList = matches;
futureMatchAdapter = isFutureMatchAdapter;
context = (Activity) cont;
inflater = LayoutInflater.from(context);
}
public int getCount()
{
return MatchAdapter.size();
}
#Override
public Object getItem(int position)
{
return MatchAdapter.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
String curPos = "";
curPos = MatchAdapter.get(position);
//times, future matches and past matches are handled differently
if(curPos.contains("Last updated:"))
time = true;
else
time = false;
if (convertView == null)
{
holder = new ViewHolder();
if(time)
{
convertView = inflater.inflate(R.layout.time_item, null);
holder.title = (TextView) convertView.findViewById(R.id.item_time);
}
else
{
if(futureMatchAdapter)
{
convertView = inflater.inflate(R.layout.feed_item, null);
holder.title = (TextView) convertView.findViewById(R.id.item_title);
}
else
{
convertView = inflater.inflate(R.layout.past_feed_item, null);
holder.title = (TextView) convertView.findViewById(R.id.item_title_past);
}
}
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
if(futureMatchAdapter)
holder.title.setText(matchList.get(position));
else
{
String matchString = matchList.get(position);
String alwaysVisible = matchString.replace("<", "vs");
alwaysVisible = alwaysVisible.replace(">", "vs");
if(!time)
alwaysVisible = alwaysVisible.substring(0, alwaysVisible.length() - 1);
holder.title.setText(alwaysVisible);
if(matchString.contains(">"))
{
String winner = matchString.substring(0, matchString.indexOf(">")) + "won!";
alwaysVisible = alwaysVisible.concat(winner);
}
else if(matchString.contains("<"))
{
String winner = matchString.substring(matchString.indexOf("<") + 2, matchString.indexOf("\n")) + " won!";
alwaysVisible = alwaysVisible.concat(winner);
}
holder.title.setOnClickListener(new pastMatchesOnclickListener(alwaysVisible)
{
public void onClick(View v)
{
((TextView) v).setText(matchWinner);
}
});
}
return convertView;
}
static class ViewHolder
{
TextView title;
TextView time;
}
}
did you try to update your list using the adapter?
dataadapter.clear();
dataadapter.addAll(allDataResult);
To show and update content in a ListView you should:
Create or find your ListView
Create your ListAdapter
Add your ListAdapter to your ListView
Add data to your ListAdapter
Call notifyDataSetChanged() on your ListAdapter.
Example:
ListView listView = (ListView) findViewById(R.id.listview);
MyListAdapter myListAdapter = new MyListAdapter();
listView.setAdapter(myListAdapter);
myListAdapter.add("Hello");
myListAdapter.add("Hi");
myListAdapter.notifyDataSetChanged();
Note: if you're using a subclass of ArrayAdapter the notifyDataSetChanged() will be called for you when you use the methods add(), addAll(), etc.

Android Color Rows

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.

Display ListView TextView based on count acting strange

I have a ListView that is being populated with collection of items using a custom adapter. One of the properties of the collection is a count, and I have two TextViews in my ListView layout, one for the text and one for the count. I'd like not to display the count TextView if the count is zero. The code I have works fine when the ListView is initially loaded, but when I scroll the ListView, the count will show on random rows and constantly change if scroll the ListView up and down. This is the code I have:
public class Main extends ListActivity
{
private static CustomAdapter adapter = null;
#Override
public void onCreate(Bundle icicle)
{
List<Item> items = new ArrayList<Item>();
items = GetItems();
adapter = new CustomAdapter();
for (Item item : items)
adapter.addItem(item);
this.setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
/* ADAPTER */
private class CustomAdapter extends BaseAdapter
{
private final List<Item> mData = new ArrayList<Item>();
private final LayoutInflater mInflater;
public CustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(Item item) {
mData.add(item);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
final Item item = (Item)this.getItem(position);
if (convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.main, parent, false);
holder.text = (TextView)convertView.findViewById(R.id.text);
holder.count = (TextView)convertView.findViewById(R.id.count);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
holder.text.setText(item.getTitle());
if (item.getCount() > 0)
holder.count.setText(item.getCount().ToString());
else
holder.count.setVisibility(View.INVISIBLE);
return(convertView);
}
}
static class ViewHolder {
TextView text, count
}
Layout:
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
/>
EDIT:
I was able to get it working by doing a hacky workaround. It seems setting the TextView's visibility to Invisible or Gone was causing the issue, so I just changed the color of the items with a zero count to the background color:
if (item.getCount() > 0)
holder.count.setText(item.getCount().ToString());
else
holder.count.setTextColor(Color.WHITE);
If anyone has a real fix, please let me know.
You should just do this:
if (item.getCount() > 0) {
holder.count.setText(item.getCount().ToString());
holder.count.setVisibility(View.VISIBLE);
}
else
holder.count.setVisibility(View.INVISIBLE);
Because you use a ViewHolder, you need to consider the fact that you might get an old View that's not showing the count. This means we need to make sure that the visibility of count is set to VISIBLE. Equally we want to hide it if the count is zero - so we change the visibility even though we might get a View that is all ready invisible.
I think you wrong a part of your code, Amend test this code:
if (item.getCount() > 0)
holder.count.setText(item.getCount());
else
holder.count.setVisibility(View.INVISIBLE);
Please go through this code you may helpful for the same.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.select);
mListUsers = getUsers();
lvUsers = (ListView) findViewById(R.id.lv_user);
s = new ListAdapter(this, R.id.lv_user, mListUsers);
lvUsers.setAdapter(s);
lvUsers.setClickable(true);
// lvUsers.setTextFilterEnabled(true);
lvUsers.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
Object o = lvUsers.getItemAtPosition(position);
UserBO obj = (UserBO) o;
Intent intent = new Intent(Select.this,Update.class);
intent.putExtra("pid", ""+obj.getId());
intent.putExtra("name", obj.getName());
//put data which you want to show and select.
startActivity(intent);
}
});
}
public ArrayList<UserBO> getUsers()
{
DBAdapter dbAdapter=DBAdapter.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
//Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM profiledatabase";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<UserBO> usersList = new ArrayList<UserBO>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
UserBO user = new UserBO();
try {
user.pid = Integer.parseInt(list.get(0));
//write code to get data from table
} catch (Exception e) {
//Log.i("***" + Select.class.toString(), e.getMessage());
}
usersList.add(user);
}
return usersList;
}
// ***ListAdapter***
private class ListAdapter extends ArrayAdapter<UserBO> {
// --CloneChangeRequired
private ArrayList<UserBO> mList;
// --CloneChangeRequired
public ListAdapter(Context context, int textViewResourceId,ArrayList<UserBO> list) {
// --CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
}
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.list_item, null);
// --CloneChangeRequired(list_item)
}
final UserBO listItem = mList.get(position);
// --CloneChangeRequired
if (listItem != null)
{
// setting list_item views
//( (TextView) view.findViewById(R.id.tv_pid) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.tv_name) ).setText( listItem.getName() );
( (TextView) view.findViewById(R.id.tv_email)).setText(listItem.getEmail());
( (TextView) view.findViewById(R.id.tv_contact) ).setText( listItem.getContact()+"" );
}}catch(Exception e)
{
//Log.i(Select.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}

Categories

Resources