This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a problem, been searching since yesterday, I post the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_wishes);
mListView = (ListView) findViewById(R.id.listId);
refreshData();
}
private void refreshData() {
wishes.clear();
dbHandler = new DatabaseHandler(getApplicationContext());
ArrayList<MyWishes> wishesFromDB = dbHandler.getWishes();
for (int i = 0; i < wishesFromDB.size(); i++){
String title = wishesFromDB.get(i).getTitle();
String content = wishesFromDB.get(i).getContent();
String date = wishesFromDB.get(i).getRecordDate();
MyWishes myWishes = new MyWishes();
myWishes.setTitle(title);
myWishes.setContent(content);
myWishes.setRecordDate(date);
wishes.add(myWishes);
}
dbHandler.close();
mWishAdapter = new WishAdapter(showWishesActivity.this, R.layout.list_row, wishes);
mListView.setAdapter(mWishAdapter);
mWishAdapter.notifyDataSetChanged();
}
public class WishAdapter extends ArrayAdapter<MyWishes>{
Activity activity;
MyWishes wish;
ArrayList<MyWishes> mData = new ArrayList<>();
int layoutRessource;
public WishAdapter(Activity act, int resource, ArrayList<MyWishes> data) {
super(act, resource, data);
activity = act;
layoutRessource = resource;
mData = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public int getPosition(MyWishes item) {
return super.getPosition(item);
}
#Nullable
#Override
public MyWishes getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null || (row.getTag()) == null){
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutRessource, null);
holder = new ViewHolder();
holder.mTitle = (TextView) findViewById(R.id.titre);
holder.mDate = (TextView) findViewById(R.id.date);
row.setTag(holder);
}else {
holder = (ViewHolder) row.getTag();
}
holder.mMyWishes = getItem(position);
holder.mTitle.setText(holder.mMyWishes.getTitle());
holder.mDate.setText(holder.mMyWishes.getRecordDate());
return row;
}
class ViewHolder{
MyWishes mMyWishes;
TextView mTitle;
TextView mContent;
TextView mDate;
TextView mId;
}
}
on the getView method, I get a NullPointerException on holder.setText.`
I post the xml too:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="12dp"
android:background="#90f96666">
<ImageView
android:id="#+id/imageViewDatabaseId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_menu_agenda"/>
<TextView
android:id="#+id/titre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="The title"
android:textStyle="bold"
android:layout_toRightOf="#+id/imageViewDatabaseId"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="The detail"
android:layout_toRightOf="#+id/imageViewDatabaseId"
android:layout_below="#+id/titleId"
android:layout_marginTop="3dp"
android:layout_marginLeft="40dp"
android:textStyle="italic"/>
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at wishlist.yassine.com.mywishlist.showWishesActivity$WishAdapter.getView(showWishesActivity.java:133)
I dont understand the problem, anyone can help me please, thank you for your time.
Instead of this
holder.mTitle = (TextView) findViewById(R.id.titre);
Try this
holder.mTitle = (TextView) convertView.findViewById(R.id.titre);
if (row == null || (row.getTag()) == null){
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutRessource, null);
holder = new ViewHolder();
holder.mTitle = (TextView) row.findViewById(R.id.titre);
holder.mDate = (TextView) row.findViewById(R.id.date);
row.setTag(holder);
}
Your view is not initialized inside getView. So:
Remove this:
holder.mTitle = (TextView) findViewById(R.id.titre);
holder.mDate = (TextView) findViewById(R.id.date);
With this:
holder.mTitle = (TextView) row.findViewById(R.id.titre);
holder.mDate = (TextView) row.findViewById(R.id.date);
In ur getView use this:
holder.mTitle = (TextView)row.findViewById(R.id.titre);
holder.mDate = (TextView)row.findViewById(R.id.date);
you have miss the view to reference
listview replace every item to your specify layout
then getview method in return view of listview item
you can use like
holder.mTitle = (TextView) row.findViewById(R.id.titre);
row is a view of layout
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null || (row.getTag()) == null){
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutRessource, null);
holder = new ViewHolder();
holder.mTitle = (TextView) row.findViewById(R.id.titre);
holder.mDate = (TextView) row.findViewById(R.id.date);
row.setTag(holder);
}else {
holder = (ViewHolder) row.getTag();
}
holder.mMyWishes = getItem(position);
holder.mTitle.setText(holder.mMyWishes.getTitle());
holder.mDate.setText(holder.mMyWishes.getRecordDate());
return row;
}
class ViewHolder{
MyWishes mMyWishes;
TextView mTitle;
TextView mContent;
TextView mDate;
TextView mId;
}
Related
I use a custom leaderboard adapter to bind the data to a recyclerview. The data is parsed like so (the data is fetched from a database, binded post execute):
for (int i = 0; i < arr.length(); ++i)
{
JSONObject obj = arr.getJSONObject(i);
String fname = obj.getString("fname");
String lname = obj.getString("lname");
int elo = Integer.parseInt(obj.getString("elo"));
int hotstreak = Integer.parseInt(obj.getString("hotstreak"));
// Add to player array
TennisUser player = new TennisUser(fname, lname, elo, hotstreak);
players.add(player);
}
Collections.sort(players, (p1, p2) -> p2.getElo() - p1.getElo());
recyclerView = findViewById(R.id.ladder_recyclerview);
LadderAdapter ladderAdapter = new LadderAdapter(getApplicationContext(), players);
recyclerView.setAdapter(ladderAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL));
If the player is on a hotstreak, indicated by 1, I set the image source to the hotstreak icon in the following code:
#Override
public void onBindViewHolder(#NonNull LadderViewHolder holder, int position) {
holder.rank.setText(String.valueOf(position + 1));
holder.fname.setText(p.get(position).getFname());
holder.lname.setText(p.get(position).getLname());
if (p.get(position).getHotstreak() == 1)
{
holder.hotstreak.setImageResource(R.drawable.hot_streak);
}
}
For testing purposes, only the first user in the list has a hotstreak, I have checked the array values after parsing and the data is correct (only the first user with hotstreak = 1). However for some reason, if anyone in the list has a hotstreak, the app also displays the last in the list with a hotstreak as well. I have debugged the process and it only enters the if statement when the condition is met. The imageview xml is:
<ImageView
android:id="#+id/img_hotstreak"
android:layout_width="20dp"
android:layout_height="22dp"
android:layout_marginStart="2dp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp"
app:layout_constraintBottom_toTopOf="#+id/lname_text"
app:layout_constraintStart_toEndOf="#+id/fname_text"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="#tools:sample/avatars" />
I can provide any more detail necessary, I'm just not sure if I'm missing something glaringly obvious. Thanks!
CustomAdapter MyClassAdapter.class
private static class ViewHolder {
TextView Id;
ImageView Image;
TextView Name;
TextView Description;
TextView Type;
TextView Cost;
TextView Count;
TextView Comment;
Button Buttonup;
Button Buttondown;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<Plate> items) {
super(context, textViewResourceId, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Plate item = getItem(position);
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.item_main, parent, false);
viewHolder = new ViewHolder();
viewHolder.Id = (TextView)convertView.findViewById(R.id.code);
viewHolder.Image = (ImageView) convertView.findViewById(R.id.image);
viewHolder.Name = (TextView) convertView.findViewById(R.id.name);
viewHolder.Description = (TextView) convertView.findViewById(R.id.description);
viewHolder.Cost = (TextView) convertView.findViewById(R.id.price);
viewHolder.Count = (TextView) convertView.findViewById(R.id.count);
viewHolder.Buttonup = (Button) convertView.findViewById(R.id.button_up);
viewHolder.Buttondown = (Button) convertView.findViewById(R.id.button_down);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (item!= null) {
viewHolder.Id.setText(String.format("%d",item.getId()));
viewHolder.Image.setImageURI(item.getImage());
viewHolder.Name.setText(String.format("%s", item.getName()));
viewHolder.Description.setText(String.format("%s", item.getDescription()));
viewHolder.Name.setText(String.format("%s", item.getName()));
viewHolder.Cost.setText(String.format("%s", item.getCost()));
viewHolder.Count.setText(String.format("%d", item.getCount()));
viewHolder.Buttonup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBHelper mydb= new DBHelper(getContext());
mydb.AddPlate(item.getId());
item.CountUp();
//update viewholder.Count
}
});
viewHolder.Buttondown.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
DBHelper mydb= new DBHelper(getContext());
mydb.RemovePlate(item.getId());
item.CountDown();
//update viewholder.Count
}
});
}
return convertView;
}
// And calls the custom ArrayAdapter from Activity
ArrayList<Plate> FullMenu;
FullMenu = mydb.getPlates("Entrees");
Plate p;
int i;
MyClassAdapter adapter = new MyClassAdapter(this,0,FullMenu);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
for (i=0; i < FullMenu.size(); i++) {
p = FullMenu.get(i);
adapter.add(p);
}
I create a adapter :
public class Adapter extends BaseAdapter implements Filterable {
Context context;
ArrayList<RowBean> data = null;
private LayoutInflater inflater;
private ValueFilter valueFilter;
private ArrayList<RowBean> mStringFilterList;
public Adapter(Context context, ArrayList<RowBean> data) {
super();
this.context = context;
this.data = data;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mStringFilterList = data;
getFilter();
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RowBeanHolder holder;
RowBean rowBean = data.get(position);
if(convertView == null){
holder = new RowBeanHolder();
convertView = inflater.inflate(R.layout.all_object_holder,null);
holder.txtTitle = (TextView) convertView.findViewById(R.id.showText);
holder.selected = (CheckBox) convertView.findViewById(R.id.checkBox12);
}else{
holder = (RowBeanHolder) convertView.getTag();
}
if(rowBean != null) {
holder.txtTitle.setText(rowBean.getTitle());
holder.selected.setChecked(rowBean.isSelected());
}
return convertView;
}
#Override
public Filter getFilter() {
if(valueFilter==null) {
valueFilter=new ValueFilter();
}
return valueFilter;
}
private class RowBeanHolder {
TextView txtTitle;
CheckBox selected;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
if(constraint!=null && constraint.length()>0){
ArrayList<RowBean> filterList=new ArrayList<>();
for(int i=0;i<mStringFilterList.size();i++){
if((mStringFilterList.get(i).getTitle().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
RowBean contacts = new RowBean();
contacts.setTitle(mStringFilterList.get(i).getTitle());
contacts.setSelected(mStringFilterList.get(i).isSelected());
filterList.add(contacts);
}
}
results.count=filterList.size();
results.values=filterList;
}else{
results.count=mStringFilterList.size();
results.values=mStringFilterList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
data=(ArrayList<RowBean>) results.values;
notifyDataSetChanged();
}
}
}
When I start my activity with this adapter I log I see this :
Process: com.maps, PID: 20174
java.lang.NullPointerException: Attempt to read from field 'android.widget.TextView com.maps.Adapter.Adapter$RowBeanHolder.txtTitle' on a null object reference
this is a line :
holder.txtTitle.setText(rowBean.getTitle());
This is a layout all_object_holder:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="#+id/checkBox12"
android:layout_width="50dp"
android:layout_height="50dp"
android:clickable="false"
android:button="#xml/setting_checkbox"
android:focusable="false"
android:gravity="center" />
<TextView
android:id="#+id/showText"
android:layout_width="395dp"
android:layout_height="wrap_content"
android:text="#string/show_choose_point"
android:textColor="#000000"
android:layout_alignBaseline="#+id/checkBox12"
android:layout_alignBottom="#+id/checkBox12"
android:layout_toRightOf="#+id/checkBox12"
android:layout_toEndOf="#+id/checkBox12" />
</RelativeLayout>
Add line
convertView.setTag(holder);
without it convertView.getTag() will return null.
if(convertView == null){
holder = new RowBeanHolder();
convertView = inflater.inflate(R.layout.all_object_holder,null);
holder.txtTitle = (TextView) convertView.findViewById(R.id.showText);
holder.selected = (CheckBox)
convertView.setTag(holder);
}
You didn't add convertView.setTag(holder). Please add it to your code and check.
NullPointerException occurs because your holder object is null sometimes. You should setTag of your convertView, just add convertView.setTag(holder); method to getView method like that:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RowBeanHolder holder;
RowBean rowBean = data.get(position);
if(convertView == null){
holder = new RowBeanHolder();
convertView = inflater.inflate(R.layout.all_object_holder,null);
holder.txtTitle = (TextView) convertView.findViewById(R.id.showText);
holder.selected = (CheckBox) convertView.findViewById(R.id.checkBox12);
convertView.setTag(holder);
}else{
holder = (RowBeanHolder) convertView.getTag();
}
if(rowBean != null) {
holder.txtTitle.setText(rowBean.getTitle());
holder.selected.setChecked(rowBean.isSelected());
}
return convertView;
}
Good luck.
Update your code with this code
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RowBeanHolder holder = new RowBeanHolder();
RowBean rowBean = data.get(position);
if(convertView == null){
convertView = inflater.inflate(R.layout.all_object_holder,null);
}
holder.txtTitle = (TextView) convertView.findViewById(R.id.showText);
holder.selected = (CheckBox) convertView.findViewById(R.id.checkBox12);
if(rowBean != null) {
holder.txtTitle.setText(rowBean.getTitle());
holder.selected.setChecked(rowBean.isSelected());
}
return convertView;
}
I have
public class MainActivity extends FragmentActivity
I wrote Loader class which implements AsyncResponse:
public class Loader implements AsyncResponse {
public Activity contextActivity;
Loader(Activity context) {
this.contextActivity = context;
}
Class "Loader" has method "DrawTabInfo" which calling from AsyncResponse callback.
public void drawTabInfo(String jsonBlob, int tabId)
{
JSONObject dataJsonObj;
PullToRefreshListView list = null;
try {
dataJsonObj = new JSONObject(jsonBlob);
JSONArray jsonData = dataJsonObj.getJSONArray("steals");
ArrayList<JSONObject> data = new ArrayList<JSONObject>();
for (int i=0;i<jsonData.length();i++){
data.add(jsonData.getJSONObject(i));
}
Adapter adapter = new Adapter(contextActivity, data);
LayoutInflater inflater = LayoutInflater.from(contextActivity);
if (tabId == 0) {
View view = inflater.inflate(R.layout.listviewlayout, null, false);
list = (PullToRefreshListView) view.findViewById(R.id.listView);
}
if (tabId == 1) {
View view = inflater.inflate(R.layout.listviewlayout2, null, false);
list = (PullToRefreshListView) view.findViewById(R.id.listView2);
}
list.setAdapter(adapter);
adapter.setNotifyOnChange(true);
Log.d("COUNT") shows - "4", what means array is built fine.
public class Adapter extends ArrayAdapter<JSONObject> {
private final Activity context;
private final ArrayList<JSONObject> profiles;
public String header;
public String preText;
public String imageURL;
static class ViewHolder {
public TextView header;
public ImageView image;
public TextView preText;
public LinearLayout linearItemLayout;
}
public Adapter(Activity context, ArrayList<JSONObject> array) {
super(context, R.layout.tab1_list_layout, array);
Log.d("ADAPTER", "SETTING ADAPTER");
this.context = context;
this.profiles = array;
Log.d("COUNT", "" + profiles.size());
}
#Override
public int getCount()
{
return profiles.size();
}
My getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Log.i("GetView Log", "Adapters GetView hasbeen called");// thats never calling
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.tab1_list_layout, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.linearItemLayout = (LinearLayout) rowView.findViewById(R.id.linearItemLayout);
viewHolder.header = (TextView) rowView.findViewById(R.id.itemHeader);
viewHolder.image = (ImageView) rowView.findViewById(R.id.itemPreImage);
viewHolder.preText = (TextView) rowView.findViewById(R.id.itemPreText);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
JSONObject item = null;
try {
item = profiles.get(position);
header = item.getString("header");
preText = item.getString("previewText");
imageURL = item.getString("previewImageUrl");
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("ADAPTER LOG", header);
holder.header.setText(header);
holder.preText.setText(preText);
int headerHeight = (int) Math.round(header.length() * 1.5);
holder.linearItemLayout.setMinimumHeight(40 + headerHeight + preText.length());
Picasso.with(context).setIndicatorsEnabled(true);
Picasso.with(context).load(imageURL).resize(140,100).into(holder.image);
return rowView;
}
In MainActivity i calling, where "this" = MainActivity;
Loader loader = new Loader(this);
loader.loadTabInfo(0);
Method getView never calling. What I'am doing wrong?
UPD:
Solved:
public void drawTabInfo(String jsonBlob, int tabId)
{
JSONObject dataJsonObj;
PullToRefreshListView list = null;
try {
dataJsonObj = new JSONObject(jsonBlob);
JSONArray jsonData = dataJsonObj.getJSONArray("steals");
ArrayList<JSONObject> data = new ArrayList<JSONObject>();
for (int i=0;i<jsonData.length();i++){
data.add(jsonData.getJSONObject(i));
}
Adapter adapter = new Adapter(contextActivity, data);
//LayoutInflater inflater = LayoutInflater.from(contextActivity);
if (tabId == 0) {
//View view = inflater.inflate(R.layout.listviewlayout, null, false);
list = (PullToRefreshListView) contextActivity.findViewById(R.id.listView);
Your code is fine .. just you need a little bit change in get view method
add a return statement.. like return rowView;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Log.d("GETVIEaW", "GETVIEW");
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.tab1_list_layout, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.linearItemLayout = (LinearLayout) rowView.findViewById(R.id.linearItemLayout);
viewHolder.header = (TextView) rowView.findViewById(R.id.itemHeader);
viewHolder.image = (ImageView) rowView.findViewById(R.id.itemPreImage);
viewHolder.preText = (TextView) rowView.findViewById(R.id.itemPreText);
rowView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) rowView.getTag();
}
viewHolder.preText.setText("Type your name");
return rowView;
}
Are you sure that Log.d() is not called? You may want to change logging scope, usually default scope is info and it doesn't show debug messages. You can try to use Log.i() or change scope.
Try posting your adapter.setNotifyOnChange(true); to handler. Follow this link
I have a row which is represented by an image, some text and a CheckBoxes. Whenever I'm trying to use the OnItemClickListener for the rows, the event won't fire up when clicking the CheckBoxes.
I also tried checkbox.onCheckedChangedListener but it gives me Null Pointer at findViewByID. I checked, the ID I am looking for is alright, no typos in there.
I'd like to make usage of this OnItemClickListener so later on I can play with the checkboxes. Any ideas?
Code:
ADAPTER:
public class FilterAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> mFilters;
private ArrayList<Integer> mPictures;
private Typeface Bebas, DroidSans;
public FilterAdapter(Context context, ArrayList<String> filters, ArrayList<Integer> pictures) {
this.mContext = context;
this.mFilters = filters;
this.mPictures = pictures;
}
#Override
public int getCount() {
return mFilters.size();
}
#Override
public Object getItem(int position) {
return mFilters.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.category_filter_item, null);
}
DroidSans = Typeface.createFromAsset(mContext.getAssets(), "fonts/DroidSans.ttf");
ImageView filter_img = (ImageView) convertView.findViewById(R.id.category_picture);
TextView filter_category = (TextView) convertView.findViewById(R.id.filter_category);
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.check_box);
filter_category.setTypeface(DroidSans);
filter_category.setText(mFilters.get(position));
filter_img.setBackgroundResource(mPictures.get(position));
return convertView;
}
}
Class where using the Adapter:
public class CheckinFilters extends Fragment {
private ListView mListView;
private FilterAdapter filterAdapter;
private ArrayList<String> l = new ArrayList<String>();
private ArrayList<Integer> drawables = new ArrayList<Integer>();
private Typeface Bebas;
private ArrayList<Integer> checkboxes = new ArrayList<Integer>();
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public CheckinFilters() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_checkin_filters, container, false);
l.add("Chill");
l.add("Eat");
l.add("Explore");
l.add("Move");
l.add("Party");
l.add("Whatever");
drawables.add(R.drawable.category_chill);
drawables.add(R.drawable.category_eat);
drawables.add(R.drawable.category_explore);
drawables.add(R.drawable.category_move);
drawables.add(R.drawable.category_party);
drawables.add(R.drawable.category_whatever);
mListView = (ListView) view.findViewById(R.id.filter_list);
filterAdapter = new FilterAdapter(view.getContext(), l, drawables);
mListView.setAdapter(filterAdapter);
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
Bebas = Typeface.createFromAsset(view.getContext().getAssets(), "fonts/BebasNeue.otf");
TextView mainHeader = (TextView) view.findViewById(R.id.filters_text);
mainHeader.setTypeface(Bebas);
SearchView filter_categories = (SearchView) view.findViewById(R.id.filter_categories);
int searchImgID = getResources().getIdentifier("android:id/search_button", null, null);
ImageView searchViewHint = (ImageView) filter_categories.findViewById(searchImgID);
searchViewHint.setImageResource(R.drawable.ab_icon_search);
int searchPlateID = filter_categories.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
View searchPlateView = filter_categories.findViewById(searchPlateID);
if (searchPlateView != null) {
searchPlateView.setBackgroundResource(R.drawable.search_location_shape);
}
int searchViewID = filter_categories.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView textView = (TextView) filter_categories.findViewById(searchViewID);
textView.setTextColor(Color.GRAY);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.check_box);
return view;
}
private void save() {
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putInt("first", checkboxes.size());
for (int i = 0; i < checkboxes.size(); i++) {
editor.remove("Status_" + i);
editor.putInt("Status_" + i, checkboxes.get(i));
}
editor.commit();
}
private void load() {
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
int size = sharedPreferences.getInt("first", 0);
for (int i = 0; i < size; i++) {
checkboxes.add(sharedPreferences.getInt("Status_" + i, 0));
}
}
#Override
public void onPause() {
super.onPause();
save();
}
#Override
public void onResume() {
super.onResume();
load();
}
}
Layout I'm inflating for Adapter:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ECF0F1">
<ImageView
android:id="#+id/category_picture"
android:layout_width="70dp"
android:layout_height="60dp"
android:background="#drawable/sm_profile"/>
<TextView
android:id="#+id/filter_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/category_picture"
android:padding="10dp"
android:text="Party"
android:textColor="#color/enloop_dark_gray"
android:textSize="18dp"/>
<CheckBox
android:id="#+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="10dp"/>
</RelativeLayout>
</RelativeLayout>
Instead of using OnItemClickListener in CheckinFilters.java, you should add that code in getView() method of FilterAdapter. You are actually adding checkbox for every row but the id for all checkbox is same, so you can't apply customized code for every checkbox.
To be able to make use of all checkboxes you can put checkbox code in getView() method because it also contains an argument called position. So you can just get the position and apply OnItemClickListener to every single checkbox. That way it will work.
public class FilterAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> mFilters;
private ArrayList<Integer> mPictures;
private Typeface Bebas, DroidSans;
public FilterAdapter(Context context, ArrayList<String> filters, ArrayList<Integer> pictures) {
this.mContext = context;
this.mFilters = filters;
this.mPictures = pictures;
}
#Override
public int getCount() {
return mFilters.size();
}
#Override
public Object getItem(int position) {
return mFilters.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.category_filter_item, null);
}
DroidSans = Typeface.createFromAsset(mContext.getAssets(), "fonts/DroidSans.ttf");
ImageView filter_img = (ImageView) convertView.findViewById(R.id.category_picture);
TextView filter_category = (TextView) convertView.findViewById(R.id.filter_category);
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.check_box);
filter_category.setTypeface(DroidSans);
filter_category.setText(mFilters.get(position));
filter_img.setBackgroundResource(mPictures.get(position));
if(position == 0) {
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
else {
}
}
});
}
//Similarly add OnClickListener to other checkboxes.
return convertView;
}
}
I have a fragment FragmentTab1 & I want to replace AllContactsFragment fragment which consists a listview & two button. The replacement performs well, but data is not showing in ListView. Data shows in log cat as well.
The replacement code Inside FragmentTab1 is:
AllContactsFragment allContactsFragment = new AllContactsFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
transaction.add(R.id.fragmentTabLayout1, allContactsFragment);
transaction.commit();
I fill up data in listview inside AllContactsFragment like:
public class AllContactsFragment extends SherlockFragment implements
OnClickListener {
ListView listViewAllContact;
Button btnAdd, btnCacel;
List<BlockNumber> contactNumberlist;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_all_contacts, container,
false);
// data are comes well & checked in Log cat
contactNumberlist = PhoneUtils.getAllContacts(getActivity());
listViewAllContact = (ListView) rootView
.findViewById(R.id.listViewAllContact);
ContactListAdapter adapter = new ContactListAdapter(getActivity(),
contactNumberlist, m_onSelectedEventCalender);
listViewAllContact.setAdapter(adapter);
if (container == null) {
return null;
}
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onClick(View v) {
}
}
I also share my ContactListAdapter adapter
public class ContactListAdapter extends BaseAdapter {
private List<BlockNumber> allContactsNumbers = null;
public Context context;
public LayoutInflater inflater;
private ViewHolder holder;
private onSelectedEventCalender m_onSelectedEventCalender;
public ContactListAdapter(Context context, List<BlockNumber> allNumberList,
onSelectedEventCalender m_onSelectedEventCalender) {
super();
this.context = context;
this.allContactsNumbers = allNumberList;
this.inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.m_onSelectedEventCalender = m_onSelectedEventCalender;
}
#Override
public int getCount() {
return allContactsNumbers.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_row, null);
convertView.setMinimumHeight(50);
holder.textViewContactName = (TextView) convertView
.findViewById(R.id.textview_contact_name);
holder.textView_Contact_Number = (TextView) convertView
.findViewById(R.id.textview_number);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.textViewContactName.setText(allContactsNumbers.get(
position).getName());
holder.textView_Contact_Number.setText(allContactsNumbers.get(
position).getNumber());
holder.textViewContactName.setTag(allContactsNumbers
.get(position));
return convertView;
}
} catch (Exception ex) {
Log.w("Exception", ex.getMessage());
}
return null;
}
public static class ViewHolder {
TextView textViewContactName;
TextView textView_Contact_Number;
// TextView textViewEventEndDate;
}
public interface onSelectedEventCalender {
void onSelectedEventCalender(BlockNumber aBlockNumber, int type);
}
}
Corresponding XML for AllContactsFragment is fragment_all_contacts.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_new" >
<!-- android:background="#80000000" -->
<RelativeLayout
android:id="#+id/relativeLayoutFragmentMain"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listViewAllContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageViewLine1" >
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dip"
android:layout_alignParentBottom="true"
android:background="#drawable/action_bar"
android:gravity="center_vertical"
android:orientation="horizontal" >
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dip"
android:layout_weight="1"
android:text="Add" />
<Button
android:id="#+id/btnCanel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dip"
android:layout_weight="1"
android:text="Home" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
May be I am missing something?
Edited: to make above code right.
remove android:layout_below="#+id/imageViewLine1" from ListView definition XML , remove return null from getView() in adapter & check the data is available or not which is set to listview.
i would try
1) in xml set your listview "above" your linear-layout-button-bar
2) after creating ContactListAdapter adapter call adapter.notifyDataSetChanged()
3) in the adapter in the first if - after convertView.setTag(holder); set return convertView;
4) create and set the adapter in the onViewCreated() Method
or
replace your listview once with an imageview and look if you will see the image, than you know for sure that the listview is the one that fails (don't forget to set a background!)
Woh! What a foolish I am? My contactNumberlist is empty because I don't add the object in the list. My Log cat misleading me. Thanks for #Ragunandan & #tom nobleman for their great afford to find mistakes.
My ContactListAdapter getView() looks like :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_row, null);
convertView.setMinimumHeight(50);
holder.textViewContactName = (TextView) convertView
.findViewById(R.id.textview_contact_name);
holder.textView_Contact_Number = (TextView) convertView
.findViewById(R.id.textview_number);
holder.imgViewContactImage = (ImageView) convertView
.findViewById(R.id.imgViewContactImage);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
if (allContactsNumbers.size() <= 0) {
holder.textViewContactName.setText("No Data");
} else {
holder = (ViewHolder) convertView.getTag();
String name = allContactsNumbers.get(position).getName();
holder.textViewContactName.setText(name);
String number = allContactsNumbers.get(position).getNumber();
holder.textView_Contact_Number.setText(number);
Uri Uri = allContactsNumbers.get(position).getImage_Uri();
if (Uri != null) {
holder.imgViewContactImage.setImageURI(Uri);
} else {
holder.imgViewContactImage.setImageResource(R.drawable.ic_no_image);
}
Log.d("Contacts in Adapter", "" + name + "" + number);
}
return convertView;
}