Adding views programmatically cause change of size in Android - java

I'm trying to add views programmatically but when i do, the size of a imageview is not the same (i've used it in another view and set by xml).
This is my function that i use to add programmatically views :
public void initClaps(int size, List<Clap> claps) {
LayoutParams params = new LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
//LayoutParams params2 = new LayoutParams(0, LayoutParams.WRAP_CONTENT,
// 33);
LayoutParams params3 = new LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1.0f);
int position = 0;
for (int i = 0; i < size; i++) {
LinearLayout layout = new LinearLayout(getActivity());
layout.setWeightSum(3.0f);
layout.setOrientation(LinearLayout.HORIZONTAL);
if (i == 0) {
View view_add = in.inflate(R.layout.adapter_claps2, null);
layout.addView(view_add, params3);
for (int j = 0; j < 2; j++) {
View view_clap = in.inflate(R.layout.adapter_claps, null);
final Clap clap = claps.get(position);
FrameLayout fl = (FrameLayout) view_clap
.findViewById(R.id.fl_adapter_claps);
SmartImageViewRound siv = (SmartImageViewRound) view_clap
.findViewById(R.id.siv_adapter_claps);
TextView tv = (TextView) view_clap
.findViewById(R.id.tv_adapter_claps);
siv.setImageUrl(clap.getMini());
tv.setText("" + clap.getNom());
fl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),
ClapDetail.class);
intent.putExtra(ClapDetail.INTENT_NOM,
clap.getNom());
getActivity().startActivity(intent);
}
});
layout.addView(view_clap, params3);
position++;
}
ll_container.addView(layout, params);
} else {
for (int j = 0; j < 3; j++) {
if(position != claps.size()){
final Clap clap = claps.get(position);
View view = in.inflate(R.layout.adapter_claps, null);
FrameLayout fl = (FrameLayout) view
.findViewById(R.id.fl_adapter_claps);
SmartImageViewRound siv = (SmartImageViewRound) view
.findViewById(R.id.siv_adapter_claps);
TextView tv = (TextView) view
.findViewById(R.id.tv_adapter_claps);
siv.setImageUrl(clap.getMini());
tv.setText("" + clap.getNom());
fl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),
ClapDetail.class);
intent.putExtra(ClapDetail.INTENT_NOM,
clap.getNom());
getActivity().startActivity(intent);
}
});
layout.addView(view, params3);
position++;
}
}
ll_container.addView(layout, params);
}
}
}

This is caused because you are passing null while inflating your views.
Lets consider the following view to be inflated(From a listViews point of view):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="15dp"
android:text="Text1" />
<TextView
android:id="#+id/text2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Text2" />
</LinearLayout>
If we are adding the above xml view to a listview as such:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflate(R.layout.item_row, null);
}
return convertView;
}
Result:
But with the right approach:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflate(R.layout.item_row, parent, false);
}
return convertView;
}
Result:
More info can be found in this nice post by Dave Smith.
You too have to replace the null with the parent viewGroup.

Related

Using a custom adapter to set an image source in Android Studio

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);
}

how to add image for headers in navigationdrawer in android

Hi in the below code in my project contains navigation drawer with expandable listview.
but everything was working fine. but want to display image for headers on leftside and arrow icon should be in right side for each header.
using json am parsing the data and in the same way want to display images for headers.
can any one help me how to do that one.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
ArrayList<Model_country> al_main = new ArrayList<>();
ExpandableListView ev_list;
CountryAdapter obj_adapter;
String TAG = "MainActivity";
private DrawerLayout mDrawerLayout;
HomeFragment fragment;
TextView tv_name;
RelativeLayout rl_menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fn_data();
init();
}
private void init() {
getSupportActionBar().hide();
ev_list = (ExpandableListView) findViewById(R.id.ev_menu);
tv_name = (TextView) findViewById(R.id.tv_name);
rl_menu = (RelativeLayout) findViewById(R.id.rl_menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
obj_adapter = new CountryAdapter(MainActivity.this, al_main);
ev_list.setAdapter(obj_adapter);
ev_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
setListViewHeight(parent, groupPosition);
return false;
}
});
setExpandableListViewHeightBasedOnChildren(ev_list);
fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("name", al_main.get(0).getStr_country());
bundle.putString("des", al_main.get(0).getAl_state().get(0).getStr_description());
bundle.putString("dish", al_main.get(0).getAl_state().get(0).getStr_name());
bundle.putString("image", al_main.get(0).getAl_state().get(0).getStr_image());
tv_name.setText(al_main.get(0).getStr_country());
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, "HomeFragment").addToBackStack("null").commit();
rl_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDrawerLayout.openDrawer(Gravity.LEFT);
}
});
}
private void setListViewHeight(ExpandableListView listView, int group) {
ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter();
int totalHeight = 0;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(),
View.MeasureSpec.EXACTLY);
for (int i = 0; i < listAdapter.getGroupCount(); i++) {
View groupItem = listAdapter.getGroupView(i, false, null, listView);
groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += groupItem.getMeasuredHeight();
if (((listView.isGroupExpanded(i)) && (i != group))
|| ((!listView.isGroupExpanded(i)) && (i == group))) {
for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
View listItem = listAdapter.getChildView(i, j, false, null,
listView);
listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
}
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
int height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
/* if (height < 10)
height = 200;*/
params.height = height;
listView.setLayoutParams(params);
listView.requestLayout();
}
private void fn_data() {
String str_data = loadJSONFromAsset();
try {
JSONObject jsonObject_country = new JSONObject(str_data);
JSONArray jsonArray_country = jsonObject_country.getJSONArray("country");
al_main = new ArrayList<>();
for (int i = 0; i < jsonArray_country.length(); i++) {
Model_country obj_country = new Model_country();
JSONObject jsonObject = jsonArray_country.getJSONObject(i);
JSONArray jsonArray_dishes = jsonObject.getJSONArray("dishes");
ArrayList<Model_Dish> al_dishes = new ArrayList<>();
for (int j = 0; j < jsonArray_dishes.length(); j++) {
JSONObject jsonObject_dishes = jsonArray_dishes.getJSONObject(j);
Model_Dish obj_dish = new Model_Dish();
obj_dish.setStr_name(jsonObject_dishes.getString("dishname"));
obj_dish.setStr_description(jsonObject_dishes.getString("description"));
obj_dish.setStr_image(jsonObject_dishes.getString("image"));
al_dishes.add(obj_dish);
}
obj_country.setAl_state(al_dishes);
obj_country.setStr_country(jsonObject.getString("name"));
// obj_country.setStr_country (jsonObject.getString("image"));
al_main.add(obj_country);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void setExpandableListViewHeightBasedOnChildren(ExpandableListView expandableListView) {
CountryAdapter adapter = (CountryAdapter) expandableListView.getExpandableListAdapter();
if (adapter == null) {
return;
}
int totalHeight = expandableListView.getPaddingTop() + expandableListView.getPaddingBottom();
for (int i = 0; i < adapter.getGroupCount(); i++) {
View groupItem = adapter.getGroupView(i, false, null, expandableListView);
groupItem.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
totalHeight += groupItem.getMeasuredHeight();
if (expandableListView.isGroupExpanded(i)) {
for (int j = 0; j < adapter.getChildrenCount(i); j++) {
View listItem = adapter.getChildView(i, j, false, null, expandableListView);
listItem.setLayoutParams(new ViewGroup.LayoutParams(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED));
listItem.measure(View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
totalHeight += listItem.getMeasuredHeight();
}
}
}
ViewGroup.LayoutParams params = expandableListView.getLayoutParams();
int height = totalHeight + expandableListView.getDividerHeight() * (adapter.getGroupCount() - 1);
if (height < 10)
height = 100;
params.height = height;
expandableListView.setLayoutParams(params);
expandableListView.requestLayout();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("dishes.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
Log.e(TAG, "Json response " + json);
return json;
}
public void fn_selectedPosition(int group, int child) {
fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("name", al_main.get(group).getStr_country());
bundle.putString("des", al_main.get(group).getAl_state().get(child).getStr_description());
bundle.putString("dish", al_main.get(group).getAl_state().get(child).getStr_name());
bundle.putString("image", al_main.get(group).getAl_state().get(child).getStr_image());
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, "HomeFragment").addToBackStack("null").commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
tv_name.setText(al_main.get(group).getStr_country());
}
activity_main:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:background="#234E6F"
android:layout_height="60dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="#ffffff"
android:layout_centerInParent="true"
android:textStyle="bold"
android:id="#+id/tv_name"/>
<ImageView
android:layout_width="25dp"
android:layout_centerVertical="true"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:src="#drawable/menu_icon"/>
<RelativeLayout
android:layout_width="40dp"
android:id="#+id/rl_menu"
android:layout_height="match_parent"></RelativeLayout>
</RelativeLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFFFFF">
<include layout="#layout/menu_layout"></include>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
You can use expandable listview for this. use custom adapter which will have textview and imageview. set image and text using expandable listview adapter. you can use custom adapter for child and parent both
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
if (view == null)
view = layoutInflater.inflate(R.layout.row_comment, viewGroup, false);
TextView username=(TextView) view.findViewById(R.id.userName);
((ImageView) view.findViewById(R.id.img_hifi)).setImageResource(R.drawable.high_5_icon_highlited);
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
if (view == null)
view = layoutInflater.inflate(R.layout.row_comment, viewGroup, false);
view.setBackgroundColor(Color.parseColor("#FFCC00"));
((TextView) view.findViewById(R.id.userName)).setText(getChild(i, i1).getUser_name() + " ");
((TextView) view.findViewById(R.id.userName)).setTextColor(Color.BLACK);
return view;
}

GridView gets disoriented while scrolling

Items in the gridView sometimes overlap or move up or down a bit.But gets fixed when scrolling back up again.Unfortunately I can't provide an image because I am new here .I am not sure if i am doing something in code.But when use listView there is no problem.
Xml for the gridView:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.gametalks.MainActivity"
android:background="#color/card_white">
<GridView
android:columnWidth="10dp"
android:numColumns="2"
android:id="#+id/listView"
android:dividerHeight="0dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:verticalSpacing="30dp"
></GridView>
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
Here is the adapter:
[public class GameAdapter extends ArrayAdapter<GameNews> {
public GameAdapter(#NonNull Context context, List<GameNews> gameNews ){
super(context, 0, gameNews);
if(gameNews == null)
{
return;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
GameNews currentNews = getItem(position);
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.grid_item, parent, false);
final ViewHolder v = new ViewHolder();
// Find the TextView in the grid_item.xml layout with the ID version_name
v.Heading = (TextView) listItemView.findViewById(R.id.title);
v.description = (TextView) listItemView.findViewById(R.id.description);
v.newsImage = (ImageView) listItemView.findViewById(R.id.image) ;
v.source = (TextView) listItemView.findViewById(R.id.source);
v.time = (TextView) listItemView.findViewById(R.id.time);
v.menuButton = (Button) listItemView.findViewById(R.id.popup);
listItemView.setTag(v);
v.menuButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(getContext(),view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.popup_menu, popup.getMenu());
popup.show();
}
});
}
ViewHolder viewHolder = (ViewHolder) listItemView.getTag();
//Setting title to current news title
viewHolder.Heading.setText(currentNews.getTitle());
viewHolder.description.setText(currentNews.getDescription());
viewHolder.newsImage.setTag(currentNews.getphotoUrl());
viewHolder.source.setText(currentNews.getSource());
viewHolder.time.setText(currentNews.getTime());
// Picasso.with(getContext()).load(currentNews.getphotoUrl()).into(viewHolder.newsImage);
if (URLUtil.isValidUrl(currentNews.getphotoUrl())) {
Picasso.with(getContext())
.load(currentNews.getphotoUrl())
.resize(350,300)
.tag(tag)
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(viewHolder.newsImage);
} else {
Picasso.with(getContext())
.load(R.drawable.right_line)
.resize(350,300)
.tag(tag)
.noPlaceholder()
.into(viewHolder.newsImage);
}
return listItemView;
}
public static class ViewHolder {
TextView Heading;
TextView description;
ImageView newsImage;
TextView source;
TextView time;
Button menuButton;
}
}][1]
If you need any other details please ask.
This happened due to the reason that i set the size of gridView items to wrap content and hence different items had different sizes.This caused unstability in the gridView.I fixed it by giving the items of the gridView a fixed dp size.And now it has no problem

android studio java NullPointerException on setText method [duplicate]

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;
}

listview data not shows in fragment

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;
}

Categories

Resources