I am creating a Recycler view in fragment, while running my app the apps automatically gets closes and show the following error:
While using the Fragment Layout it's showing error, apart from that when i use the empty layout, the process is working normally and easily gets run.
Process: com.example.lenovo.skanda, PID: 9018
> java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.lenovo.skanda.Listitem.getHead()' on a
> null object reference
> at `enter code here`com.example.lenovo.skanda.MyAdapter.onBindViewHolder(MyAdapter.java:35)
> at com.example.lenovo.skanda.MyAdapter.onBindViewHolder(MyAdapter.java:12)
Need Help..!!
Fragment_stories.xml
<?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"
android:id="#+id/fragment_container">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:padding="10dp"
android:layout_margin="#dimen/cardview_default_elevation"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textViewHead"
android:text="Heading"
android:textSize="15dp"
android:gravity="center"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textViewDesc"
android:text="Description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
StoriesFragment.java
public class StoriesFragment extends Fragment {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<Listitem> listitems;
String[] head = new String[]{"apple", "banana", "curry", "dog"};
String[] desc = new String[]{"This is article 1", "This is article 2", " This is article 3”, "this is article 4"};
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stories, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
listitems = new ArrayList<>();
for (int i = 0; i <= 3; i++) {
new Listitem(
head[i],
desc[i]);
Listitem listitem = null;
listitems.add(listitem);
}
adapter = new MyAdapter(listitems, getActivity());
recyclerView.setAdapter(adapter);
return view;
}
}
Listitem.java
package com.example.lenovo.skanda;
public class Listitem {
private String head;
private String desc;
public Listitem(String head, String desc) {
this.head = head;
this.desc = desc;
}
public String getHead() {
return head;
}
public String getDesc() {
return desc;
}
}
MyAdapter.java
package com.example.lenovo.skanda;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Listitem> listitems;
private Context context;
public MyAdapter(List<Listitem> listitems, Context context) {
this.listitems = listitems;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Listitem listitem = listitems.get(position);
holder.textViewHead.setText(listitem.getHead());
holder.textViewDesc.setText(listitem.getDesc());
}
#Override
public int getItemCount() {
return listitems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView textViewHead;
public TextView textViewDesc;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
}
}
}
Your problem is with your for cycle. You are adding nullable values to your list:
for (int i = 0; i <= 3; i++) {
new Listitem(
head[i],
desc[i]);
Listitem listitem = null;
listitems.add(listitem);
}
It should be:
for (int i = 0; i <= 3; i++) {
Listitem listitem = new Listitem(
head[i],
desc[i]);
listitems.add(listitem);
}
Related
I am new with Android Studio, and I would like to try a listview with pictures on the left shown below. I managed to make such a list with a simple list item, but when I changed the simple item list with an ActivityList, it does not work anymore.
How can I change the ArrayList to combine imageviews with the names? I think it could be possible by using a new class which contains the imageview and name instead of strings.
Code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView friendsListView = findViewById(R.id.friendListView);
final ArrayList<String> myFriends = new ArrayList<String>(asList("Mark","Jane","Sussy","Jan"));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.activity_list_item
, myFriends);
friendsListView.setAdapter(arrayAdapter);
friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Hello " + myFriends.get(i), Toast.LENGTH_LONG).show();
}
});
}
}
You're right, you need to create a model class for your list item; this model class contains things that differ from item to item; for instance in your shared picture, a list item has a typical of a picture and a title; and so your model class.
Next, instead of having ArrayList<String>, use ArrayList<Item>; where Item is the model class
Third, you need to create a custom adapter that extends from ArrayAdapter<Item>; that is because you can't use the built-in list item layout "android.R.layout.activity_list_item", because it just offers you with a single string; and now you need to accompany a picture with it.
Below is a simple demo
Model class (Item.java)
class Item {
private int mPicture;
private String mTitle;
int getPicture() {
return mPicture;
}
Item(int picture, String title) {
mPicture = picture;
mTitle = title;
}
String getTitle() {
return mTitle;
}
}
List View Adapter (ListViewAdapter.java)
public class ListViewAdapter extends ArrayAdapter<Item> {
ListViewAdapter(#NonNull Context context, ArrayList<Item> items) {
super(context, 0, items);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if (listItem == null) {
listItem = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
// Get the {#link Word} object located at this position in the list
Item currentItem = getItem(position);
ImageView picture = listItem.findViewById(R.id.IvPicture);
picture.setBackgroundResource(currentItem.getPicture());
TextView title = listItem.findViewById(R.id.tvTitle);
title.setText(currentItem.getTitle());
return listItem;
}
}
Activity class
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Item> items = new ArrayList<>();
items.add(new Item(R.drawable.item1, "Item1"));
items.add(new Item(R.drawable.item2, "Item2"));
items.add(new Item(R.drawable.item3, "Item3"));
ListViewAdapter adapter = new ListViewAdapter(this, items);
ListView listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
}
}
Activity Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
List item layout (list_item.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/IvPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item" />
</LinearLayout>
You have to have 3 images into res/drawable named item1, item2, and item3
Hope this satisfies your need.
activity_main.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#color/grey_300"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
</RelativeLayout>
cards_layout.xml code:
<android.support.v7.widget.CardView
android:id="#+id/card_view"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#color/color_white"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="5dp"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/imageView"
android:tag="image_tag"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:src="#drawable/ic_launcher"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_weight="2"
android:orientation="vertical"
>
<TextView
android:id="#+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Android Name"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="#+id/textViewVersion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Android Version"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
menu_main.xml code:
<menu 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"
tools:context=".MainActivity">
<item android:id="#+id/add_item"
android:title="Add"
android:orderInCategory="100"
app:showAsAction="always"/>
</menu>
MainActivity.java
package com.journaldev.recyclerviewcardview;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<DataModel> data;
static View.OnClickListener myOnClickListener;
private static ArrayList<Integer> removedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myOnClickListener = new MyOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<DataModel>();
for (int i = 0; i < MyData.nameArray.length; i++) {
data.add(new DataModel(
MyData.nameArray[i],
MyData.versionArray[i],
MyData.id_[i],
MyData.drawableArray[i]
));
}
removedItems = new ArrayList<Integer>();
adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
}
private static class MyOnClickListener implements View.OnClickListener {
private final Context context;
private MyOnClickListener(Context context) {
this.context = context;
}
#Override
public void onClick(View v) {
removeItem(v);
}
private void removeItem(View v) {
int selectedItemPosition = recyclerView.getChildPosition(v);
RecyclerView.ViewHolder viewHolder
= recyclerView.findViewHolderForPosition(selectedItemPosition);
TextView textViewName
= (TextView) viewHolder.itemView.findViewById(R.id.textViewName);
String selectedName = (String) textViewName.getText();
int selectedItemId = -1;
for (int i = 0; i < MyData.nameArray.length; i++) {
if (selectedName.equals(MyData.nameArray[i])) {
selectedItemId = MyData.id_[i];
}
}
removedItems.add(selectedItemId);
data.remove(selectedItemPosition);
adapter.notifyItemRemoved(selectedItemPosition);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_item) {
//check if any items to add
if (removedItems.size() != 0) {
addRemovedItemToList();
} else {
Toast.makeText(this, "Nothing to add", Toast.LENGTH_SHORT).show();
}
}
return true;
}
private void addRemovedItemToList() {
int addItemAtListPosition = 3;
data.add(addItemAtListPosition, new DataModel(
MyData.nameArray[removedItems.get(0)],
MyData.versionArray[removedItems.get(0)],
MyData.id_[removedItems.get(0)],
MyData.drawableArray[removedItems.get(0)]
));
adapter.notifyItemInserted(addItemAtListPosition);
removedItems.remove(0);
}
}
CustomAdapter.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private ArrayList<DataModel> dataSet;
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView textViewName;
TextView textViewVersion;
ImageView imageViewIcon;
public MyViewHolder(View itemView) {
super(itemView);
this.textViewName = (TextView) itemView.findViewById(R.id.textViewName);
this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public CustomAdapter(ArrayList<DataModel> data) {
this.dataSet = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_layout, parent, false);
view.setOnClickListener(MainActivity.myOnClickListener);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {
TextView textViewName = holder.textViewName;
TextView textViewVersion = holder.textViewVersion;
ImageView imageView = holder.imageViewIcon;
textViewName.setText(dataSet.get(listPosition).getName());
textViewVersion.setText(dataSet.get(listPosition).getVersion());
imageView.setImageResource(dataSet.get(listPosition).getImage());
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
DataModel.java
public class DataModel {
String name;
String version;
int id_;
int image;
public DataModel(String name, String version, int id_, int image) {
this.name = name;
this.version = version;
this.id_ = id_;
this.image=image;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public int getImage() {
return image;
}
public int getId() {
return id_;
}
}
MyData.java
public class MyData {
static String[] nameArray = {"Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich","JellyBean", "Kitkat", "Lollipop", "Marshmallow"};
static String[] versionArray = {"1.5", "1.6", "2.0-2.1", "2.2-2.2.3", "2.3-2.3.7", "3.0-3.2.6", "4.0-4.0.4", "4.1-4.3.1", "4.4-4.4.4", "5.0-5.1.1","6.0-6.0.1"};
static Integer[] drawableArray = {R.drawable.cupcake, R.drawable.donut, R.drawable.eclair,
R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb, R.drawable.ics,
R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop,R.drawable.marsh};
static Integer[] id_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView friendsListView = findViewById(R.id.friendListView);
final ArrayList<Item> items = new ArrayList<>();
items.add(new Item(R.drawable.abc, "Item1"));
items.add(new Item(R.drawable.def, "Item2"));
ListViewAdapter adapter = new ListViewAdapter(this, items);
ListView.setAdapter(adapter);
friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Hello " + items.get(i), Toast.LENGTH_LONG).show();
}
});
}
}
Can someone tell me what's wrong with this adapter? I'm getting an empty RecyclerView but a list that has 11 items in it? we have checked the customer class and the MainActivity and it seems to be correct. we log the customers.size in the getitems and find that there should be no trouble. could it be something wrong with the viewHolder class?
package com.example.jenso.test1yay;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import static android.content.ContentValues.TAG;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Customer> customers;
private Context context;
public MyAdapter(List<Customer> listItems ,Context context){
this.customers = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item,parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Customer customer = customers.get(position);
if (holder != null) {
holder.textViewHead.setText(customer.getName());
holder.textViewDesc.setText(customer.getLastName());
}
}
#Override
public int getItemCount() {
Log.d(TAG, "getItemCount: "+ customers.size());
return customers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView textViewHead;
public TextView textViewDesc;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
}
}
}
package com.example.jenso.test1yay;
import android.nfc.Tag;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<Customer> customers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
customers = new ArrayList<>();
for(int i = 1; i <= 10; i++){
Customer customer = new Customer("Jens" + (i+1),
"Svensson"
);
customers.add(customer);
}
adapter = new MyAdapter(customers, this);
recyclerView.setAdapter(adapter);
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.constraint.ConstraintLayout
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/textViewDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="2dp"
android:text="Description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textViewHead" />
<TextView
android:id="#+id/textViewHead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="2dp"
android:text="Heading"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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.jenso.test1yay.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
tools:listitem="#layout/list_item" />
</android.support.constraint.ConstraintLayout>
Try change size of TextView android:layout_width="0dp" to 100dp
Late to the party, but try to pass the activity's Context into the adapter and then use that context in LayoutInflater.from instead of parent.getContext()
i make some correction in your code try it.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Customer> customers=new ArrayList<>();
private Context context;
public MyAdapter(List<Customer> listItems, Context context) {
this.customers = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Customer customer = customers.get(position);
if (holder != null) {
holder.textViewHead.setText(customer.getName());
holder.textViewDesc.setText(customer.getLastName());
}
}
#Override
public int getItemCount() {
Log.d(TAG, "getItemCount: " + customers.size());
return customers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewHead;
public TextView textViewDesc;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
}
}
}
in main activity..
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyAdapter adapter;
private List<Customer> customers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
customers = new ArrayList<>();
for(int i = 1; i <= 10; i++){
Customer customer = new Customer("Jens" + (i+1),
"Svensson"
);
customers.add(customer);
}
adapter = new MyAdapter(customers, this);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
I have 6 fragments in a Sliding tab layout. All of them have RecyclerView implemented in them. I have populated the RecyclerView. But I one of the fragments does not allow me to scroll, but the rest are working fine.
See the gif below:
This is my problem
Genres.java
public class Genres extends Fragment {
private static final String TAG = "Genres";
RecyclerView recyclerView_genre;
GenresAdapter genresAdapter;
ArrayList<GenresModel> Genrelist = new ArrayList<>();
long genreId;
String genreName;
Cursor genrecursor;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.genres_activity, container, false);
recyclerView_genre = view.findViewById(R.id.recyclerView_genre);
recyclerView_genre.setHasFixedSize(true);
LinearLayoutManager genreLayout = new LinearLayoutManager(getContext());
recyclerView_genre.setLayoutManager(genreLayout);
String[] proj1 = {MediaStore.Audio.Genres.NAME, MediaStore.Audio.Genres._ID};
genrecursor=getActivity().getContentResolver().query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI,proj1,null, null, null);
if (genrecursor != null) {
if (genrecursor.moveToFirst()) {
do {
genreId = genrecursor.getLong(genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID));
genreName = genrecursor.getString(genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME));
GenresModel genresModel = new GenresModel(genreId,genreName );
Genrelist.add(genresModel);
Collections.sort(Genrelist, new Comparator<GenresModel>() {
#Override
public int compare(GenresModel lhs, GenresModel rhs) {
return lhs.getGenreName().compareTo(rhs.getGenreName());
}
});
} while (genrecursor.moveToNext());
}
}
genrecursor.close();
genresAdapter = new GenresAdapter(getContext(),Genrelist);
recyclerView_genre.setAdapter(genresAdapter);
genresAdapter.notifyDataSetChanged();
return view;
}
GenresAdapter.java
public class GenresAdapter extends RecyclerView.Adapter<GenresAdapter.GenresHolder> {
Context gContext;
ArrayList<GenresModel> GenreList = new ArrayList<>();
public GenresAdapter(Context gContext, ArrayList<GenresModel> genreList) {
this.gContext = gContext;
GenreList = genreList;
}
#Override
public GenresAdapter.GenresHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view3 = LayoutInflater.from(gContext).inflate(R.layout.row_genre, parent, false);
return new GenresHolder(view3);
}
#Override
public void onBindViewHolder(GenresAdapter.GenresHolder holder, int position) {
final GenresModel genresModel1 = GenreList.get(position);
holder.genreText.setText( genresModel1.getGenreName());
}
#Override
public int getItemCount() {
return GenreList.size();
}
public class GenresHolder extends RecyclerView.ViewHolder {
TextView genreText;
public GenresHolder(View itemView) {
super(itemView);
genreText = itemView.findViewById(R.id.genreText);
}
}
}
activity_genre.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView_genre"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="130dp"
>
</android.support.v7.widget.RecyclerView>
</LinearLayout>
row_genre.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:paddingTop="35dp"
>
<TextView
android:id="#+id/genreText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textSize="14sp"
/>
</LinearLayout>
I found out the solution myself. Actually the the problem was with the viewpager transformation. I applied https://github.com/geftimov/android-viewpager-transformers/wiki/CubeOutTransformer to my viewpager and for some reason my first 3 fragments were working and rest were not!
i am working on an assignment on listview in fragments.
i have a fragment class
i have to Bind the List/Collection of Contacts with listView.
My listview must be in fragment
public class Listviewfragment extends Fragment {
private ArrayList<Contacts> list = new ArrayList<Contacts>();
private ListView l;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
for (int i = 0; i < 100; i++) {
list.add(new Contacts("omar"+i,"03214"+i));
}
l = (ListView) view.findViewById(R.id.listview1);
l.setAdapter(new CustomAdapter(getActivity(),list));
}
}
CustomAdapter
public class CustomAdapter extends ArrayAdapter {
#NonNull
private final Context context;
#NonNull
private final ArrayList<Contacts> list;
private TextView t1,t2;
public CustomAdapter(#NonNull Context context, #NonNull ArrayList<Contacts> list) {
super(context, 0, list);
this.context = context;
this.list = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull
ViewGroup parent) {
Contacts u = (Contacts) getItem(position);
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listitems, parent, false);
t1 = (TextView) convertView.findViewById(R.id.textView1);
t2 = (TextView) convertView.findViewById(R.id.textView2);
t1.setText(u.getName());
t2.setText(u.getNumber());
return convertView;
}
}
Contacts class
public class Contacts {
private String name;
private String number;
public Contacts(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
}
There are no errors but but "Application has stopped"
layout for main activity that includes
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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.hp.myapplication.MainActivity">
<fragment
android:id="#+id/fragment3"
android:name="com.example.hp.myapplication.Listviewfragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout="#layout/listviewfragment"/>
</android.support.constraint.ConstraintLayout>
layout for fragment
<?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">
<ListView
android:id="#+id/listview1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
i dont know what did i make wrong in it
check the last line in the first xml posted
</android.support.constraint.ConstraintLayou t>
you have a "space" in ConstraintLayout fix it to:
</android.support.constraint.ConstraintLayout>
So I have this list of city objects (which contain an image, the name of the city, and a integer value). And for each of these city objects I want to programatically create a new cardView and insert it into a fragment. Currently, nothing shows up...
Here is my fragment xml code.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp"
android:id="#+id/fragCards_LL">
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Here is the code for my fragment activity.
public class FragmentCards extends Fragment
{
private ArrayList<CityFolders> cityFolders = new ArrayList<>();
private OnCardsFragmentListener mListener;
private LinearLayout linearLayout;
private View view;
public FragmentCards() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_fragment_cards, container, false);
setUpLinearLayout();
setUpCityFolders();
//TextView myText = (TextView) view.findViewById(R.id.fragCards_numberOfCardsTextContent);
//Toast.makeText(getActivity(), myText.getText(), Toast.LENGTH_SHORT).show();
return inflater.inflate(R.layout.fragment_fragment_cards, container, false);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnCardsFragmentListener)
{
mListener = (OnCardsFragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnCheeseCategoriesFragmentListener");
}
}
private void setUpLinearLayout()
{
linearLayout = (LinearLayout) view.findViewById(R.id.fragCards_LL);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new NestedScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
private void setUpCityFolders()
{
if(!Global_Class.getInstance().getValue().cityFoldersArrayList.isEmpty())
{
cityFolders = Global_Class.getInstance().getValue().cityFoldersArrayList;
for(CityFolders cityFolder : cityFolders)
{
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(64,64,64,64);
lp.height = 200;//180dp = 720pixels
lp.width = 1408;//330dp = 1320 pixels.
CardView cityCardView = new CardView(getActivity());// ERROR
cityCardView.setBackgroundColor(000000);
cityCardView.setLayoutParams(lp);
linearLayout.addView(cityCardView, 0);
}
}
}
public interface OnCardsFragmentListener
{
void disableCollapse();
}
}
So, don't know what I am doing wrong here... hope someone can help, maybe point out what im doing wrong?
Also, in my cardView, going horizontally, I want to have an imageview, then a textview, followed by another textview. How would I inflate those parts of the cardView and fill them with an image, and 2 texts from my cityFolder object? Hope you guys can help me with an answer!
Cheers
EDIT:
So i implemented a recycler view and..nothing shows up on the screen... This recycler view just holds simple views with each view having an imageview and a textview, and nothing shows up..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp"
android:id="#+id/fragCards_LL">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragCards_RecyclerView">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Here is my xml code for the view for each item in the recycler view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/fullstar"
android:id="#+id/fragCardsCity_imageview"
android:layout_gravity="center_vertical"
android:padding="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Star City"
android:layout_gravity="center_vertical"
android:id="#+id/fragCardsCity_textView"
android:padding="8dp"/>
</LinearLayout>
And finally, here is my java code.
public class FragmentCards extends Fragment
{
private ArrayList<CityFolders> cityFolders = new ArrayList<>();
private LinearLayout linearLayout;
private View rootView;
private RecyclerView recyclerView;
private CityViewAdapter cityAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_cards, container, false);
linearLayout = (LinearLayout) rootView.findViewById(R.id.fragCards_LL);
recyclerView = (RecyclerView) rootView.findViewById(R.id.fragCards_RecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
cityAdapter = new CityViewAdapter(getActivity(),getData());
recyclerView.setAdapter(cityAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
public static ArrayList<myData> getData()
{
ArrayList<myData> data = new ArrayList<>();
int[] icons = {R.drawable.fullstar,R.drawable.fullstar,R.drawable.fullstar,R.drawable.fullstar};
String[] titles = {"San Francisco","Seattle","Tokyo","Osaka"};
for(int i = 0; i < titles.length && i < icons.length; i++)
{
myData current = new myData();
current.iconId = icons[i];
current.cityName = titles[i];
data.add(current);
}
return data;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private static class myData
{
private int iconId;
private String cityName;
}
private class CityViewAdapter extends RecyclerView.Adapter<CityViewAdapter.MyViewHolder>
{
private LayoutInflater inflater;
private ArrayList<myData> infoList = new ArrayList<>();
public CityViewAdapter(Context context, ArrayList<myData> data)
{
inflater = LayoutInflater.from(context);
this.infoList = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = inflater.inflate(R.layout.fragment_cards_cityview,parent,false);
MyViewHolder holder = new MyViewHolder(view);//special way to avoid "findViewById everytime you make a view
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position)
{
myData current = infoList.get(position);
holder.title.setText(current.cityName);
holder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView title;
ImageView icon;
public MyViewHolder(View itemView)
{
super(itemView);
title = (TextView) itemView.findViewById(R.id.fragCardsCity_textView);
icon = (ImageView) itemView.findViewById(R.id.fragCardsCity_imageview);
}
}
}
}