RecyclerView NullPointerException - java

in the moment Iam playing arround with the RecyclerView. The whole time I get some NullPointer Exceptions but I can't find why.
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.lueth.erik.birthdays/de.lueth.erik.birthdays.TodaysBirthdays.TodaysBirthdaysActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5349)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at de.lueth.erik.birthdays.TodaysBirthdays.TodaysBirthdaysActivity.onCreate(TodaysBirthdaysActivity.java:23)
at android.app.Activity.performCreate(Activity.java:6020)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2284)...
Here is my TodaysBirthdaysActivity.class
The onCreate part looks like that one that Google is showing in their RecyclerView tutorial.
public class TodaysBirthdaysActivity extends Activity{
private RecyclerView recList;
private RecyclerView.Adapter adp;
private RecyclerView.LayoutManager llm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_birthday_list);
recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
llm = new LinearLayoutManager(this);
recList.setLayoutManager(llm);
adp = new Adapter(createList(30));
recList.setAdapter(adp);
}
private List<ContactInfo> createList(int size) {
List<ContactInfo> result = new ArrayList<ContactInfo>();
for (int i=1; i <= size; i++) {
ContactInfo ci = new ContactInfo();
ci.name = ContactInfo.NAME_PREFIX + i;
ci.surname = ContactInfo.SURNAME_PREFIX + i;
ci.birthday = ContactInfo.Birthday_PREFIX + i ;
result.add(ci);
}
return result;
}}
Here is my activity_birthday_list.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".TodaysBirthdaysActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent"
/></RelativeLayout>
Here my Adapter.class
public class Adapter extends RecyclerView.Adapter<ContactViewHolder> {
private List<ContactInfo> contactList;
public Adapter(List<ContactInfo> contactList) {
this.contactList = contactList;
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) {
ContactInfo ci = contactList.get(i);
contactViewHolder.vName.setText(ci.name);
contactViewHolder.vSurname.setText(ci.surname);
contactViewHolder.vBirthday.setText(ci.birthday);
contactViewHolder.vTitle.setText(ci.name + " " + ci.surname);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.contact_card, viewGroup, false);
return new ContactViewHolder(itemView);
}}
here my ContactInfo.java
public class ContactInfo {
protected String name;
protected String surname;
protected String birthday;
protected static final String NAME_PREFIX = "Name_";
protected static final String SURNAME_PREFIX = "Surname_";
protected static final String Birthday_PREFIX = "Birthday_";}
and here my ContentViewHolder.java
public class ContactViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vSurname;
protected TextView vBirthday;
protected TextView vTitle;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vSurname = (TextView) v.findViewById(R.id.txtSurname);
vBirthday = (TextView) v.findViewById(R.id.txtBirthday);
vTitle = (TextView) v.findViewById(R.id.title);
}}
and the xml for the card contact_card.xml
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#color/cardview_dark_background"
android:text="contact det"
android:gravity="center_vertical"
android:textColor="#android:color/white"
android:textSize="14dp"/>
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/title"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"/>
<TextView
android:id="#+id/txtSurname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Surname"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/txtName"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"/>
<TextView
android:id="#+id/txtBirthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Birthday"
android:textSize="10dp"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="150dp"
android:layout_alignBaseline="#id/txtName"/>
</RelativeLayout> </android.support.v7.widget.CardView>

It's all in your logcat output:
at de.lueth.erik.birthdays.TodaysBirthdays.TodaysBirthdaysActivity.onCreate(TodaysBirthdaysActivity.java:23)
That line TodaysBirthdaysActivity.java:23 gives you NPE. Which means, your variable recList is null. Why? Most probably, because there is no object with id R.id.cardList inside layout R.layout.activity_birthday_list.

Related

BUG, activity does not load fragment with firebase data [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Avoiding NullPointerException in Java
(66 answers)
Closed 8 months ago.
my application so far is like this: in ActivityHome, it opens the Fragments using a "FragmentContainerView", my FragmentHome loads the firebase videos in a ViewPage2, using the design of an xml file
The problem is that after finishing the class files, the application does not run and presents the error in onCreate(Home.java), I could not solve the error or find the problem
Could someone point out how to solve this BUG?
layout/Activity_Home:
<androidx.coordinatorlayout.widget.CoordinatorLayout
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=".Home">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/nav_host_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#+id/nav_inferior"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/nav_main"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_baseline_add_24"
app:maxImageSize="50dp"
android:backgroundTint="#3f3f3f"
app:borderWidth="0dp"
app:layout_anchor="#id/nav_inferior"
android:contentDescription="#string/nav_post" />
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/nav_inferior"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:fabCradleRoundedCornerRadius="20dp"
app:fabCradleMargin="10dp"
>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav_inferior"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
app:menu="#menu/menu_inferior"
android:layout_marginEnd="20dp"
app:itemIconTint="#color/nav_item_bg"
app:itemTextColor="#color/nav_item_bg"
/>
</com.google.android.material.bottomappbar.BottomAppBar>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Home.java
public class Home extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
ActivityHomeBinding binding;
private NavHostFragment navHostFragment;
private NavController navController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
binding = ActivityHomeBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
IniciarComponentes();
IniciarNavegacao();
IniciarBadge();
}
private void IniciarNavegacao(){
navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
navController = navHostFragment.getNavController();
NavigationUI.setupWithNavController(binding.bottomNavInferior, navController);
navController.addOnDestinationChangedListener((navController, navDestination, bundle) -> {
if (navDestination.getId() == R.id.nav_painel){
BadgeDrawable badgeDrawable = binding.bottomNavInferior.getBadge(R.id.bottom_nav_inferior);
if (badgeDrawable != null){
badgeDrawable.setVisible(false);
badgeDrawable.clearNumber();
}
}
});
}
private void IniciarBadge(){
BadgeDrawable badge = binding.bottomNavInferior.getOrCreateBadge(R.id.nav_painel);
badge.setVisible(true);
badge.setNumber(99);
badge.setBackgroundColor(ContextCompat.getColor(this,R.color.colorError));
badge.setBadgeTextColor(ContextCompat.getColor(this, com.denzcoskun.imageslider.R.color.text_shadow_white));
}
private void IniciarComponentes(){
bottomNavigationView = findViewById(R.id.bottom_nav_inferior);
bottomNavigationView.setBackground(null);
}
}
layout/FragmentHome
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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=".fragments.HomeFragment">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/homeVideos"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</FrameLayout>
fragmente/FragmentHome.java
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
VideosConvert videosConvert;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ViewPager2 viewPager2 = binding.homeVideos;
FirebaseRecyclerOptions<VideosDados> options =
new FirebaseRecyclerOptions.Builder<VideosDados>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Videos"), VideosDados.class)
.build();
videosConvert = new VideosConvert(options);
viewPager2.setAdapter(videosConvert);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = FragmentHomeBinding.inflate(inflater,container, false);
View root = binding.getRoot();
return root;
}
#Override
public void onStart() {
super.onStart();
videosConvert.startListening();
}
#Override
public void onStop() {
super.onStop();
videosConvert.stopListening();
}
}
layout/videoDesign
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
android:background="#000">
<VideoView
android:id="#+id/videoView"
android:layout_width="0dp"
android:layout_height="0dp"
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="1.0" />
<ProgressBar
android:id="#+id/videoProgressBar"
android:layout_width="30dp"
android:layout_height="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.888">
<TextView
android:id="#+id/textoTituloVideo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="6.00sp"
android:layout_marginBottom="7.80sp"
android:fontFamily="sans-serif-medium"
android:textColor="#android:color/white"
android:paddingStart="5dp"
android:paddingTop="5dp"
android:paddingEnd="5dp"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="15"
android:text="Título"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textoDescricaoVideo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="7.80sp"
android:layout_marginEnd="46.8dp"
android:layout_marginBottom="20.80dp"
android:textColor="#android:color/white"
android:fontFamily="#font/calibri"
android:paddingStart="5dp"
android:paddingTop="5dp"
android:paddingEnd="5dp"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="15"
android:text="Descrição do vídeo"
android:textSize="16sp" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
VideoConvert.java
public class VideosConvert extends FirebaseRecyclerAdapter<VideosDados, VideosConvert.myviewholder> {
public VideosConvert(#NonNull FirebaseRecyclerOptions<VideosDados> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull VideosDados model) {
holder.setdata(model);
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_design,parent,false);
return new myviewholder(view);
}
public class myviewholder extends RecyclerView.ViewHolder {
VideoView videoView;
TextView titolo,desc;
ProgressBar progressBar;
public myviewholder(#NonNull View itemView) {
super(itemView);
videoView=(VideoView)itemView.findViewById(R.id.videoView);
titolo=(TextView)itemView.findViewById(R.id.textoTituloVideo);
desc=(TextView)itemView.findViewById(R.id.textoDescricaoVideo);
progressBar=(ProgressBar)itemView.findViewById(R.id.videoProgressBar);
}
public void setdata(VideosDados model) {
videoView.setVideoPath(model.getUrl());
titolo.setText(model.getTitle());
desc.setText(model.getDesc());
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
progressBar.setVisibility(View.GONE);
mp.start();
}
});
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.start();
}
});
}
}
}
VideoDados.java
public class VideosDados {
String desc,title,url;
public VideosDados(String desc, String title, String url) {
this.desc = desc;
this.title = title;
this.url = url;
}
VideosDados() {
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
after hours of failing to resolve, it seems impossible to resolve.
thanks for the time and help
Debug
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.meinlowe.souldiabah, PID: 30521
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.meinlowe.souldiabah/com.meinlowe.souldiabah.Home}: android.view.InflateException: Binary XML file line #11 in com.meinlowe.souldiabah:layout/activity_home: Binary XML file line #11 in com.meinlowe.souldiabah:layout/activity_home: Error inflating class androidx.fragment.app.FragmentContainerView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4035)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4201)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2438)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8663)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
Caused by: android.view.InflateException: Binary XML file line #11 in com.meinlowe.souldiabah:layout/activity_home: Binary XML file line #11 in com.meinlowe.souldiabah:layout/activity_home: Error inflating class androidx.fragment.app.FragmentContainerView
Caused by: android.view.InflateException: Binary XML file line #11 in com.meinlowe.souldiabah:layout/activity_home: Error inflating class androidx.fragment.app.FragmentContainerView
Caused by: java.lang.NullPointerException: Attempt to read from field 'androidx.viewpager2.widget.ViewPager2 com.meinlowe.souldiabah.databinding.FragmentHomeBinding.homeVideos' on a null object reference
at com.meinlowe.souldiabah.fragments.HomeFragment.onCreate(HomeFragment.java:27)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2981)
at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:474)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:257)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1840)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1764)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1701)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2849)
at androidx.fragment.app.FragmentManager.dispatchCreate(FragmentManager.java:2773)
at androidx.fragment.app.Fragment.onCreate(Fragment.java:1913)
at androidx.navigation.fragment.NavHostFragment.onCreate(NavHostFragment.kt:169)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2981)
at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:474)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:257)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1840)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1764)
at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1670)
at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:323)
at androidx.fragment.app.FragmentContainerView.<init>(FragmentContainerView.kt:158)
at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:53)
at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:295)
E/AndroidRuntime: at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:274)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1073)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1001)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1127)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
at android.view.LayoutInflater.inflate(LayoutInflater.java:686)
at android.view.LayoutInflater.inflate(LayoutInflater.java:538)
at com.meinlowe.souldiabah.databinding.ActivityHomeBinding.inflate(ActivityHomeBinding.java:56)
at com.meinlowe.souldiabah.databinding.ActivityHomeBinding.inflate(ActivityHomeBinding.java:50)
at com.meinlowe.souldiabah.Home.onCreate(Home.java:28)
at android.app.Activity.performCreate(Activity.java:8290)
at android.app.Activity.performCreate(Activity.java:8270)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4009)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4201)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2438)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8663)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)

Add ArrayLIst to Recyclerview

I have an AlertDialog in it there used to be a ListView in which the contents of the ArrayList were displayed. For beauty, I decided to replace it with Recyclerview, Card and the problems started.
Items are added to ArrayList <String> mainListWord during the work and they should be included in the Recyclerview cards. The problem is that either the entire list falls into one card at once, or each next card contains the previous elements + 1. For example: the first card: 1 element, the second card: 2 elements, etc.
How to implement it so that when a new element is added to the array, it will be placed in its own card?
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<EditText
android:id="#+id/innerText"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_centerInParent="true"/>
<Button
android:id="#+id/press"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Press"
android:layout_below="#id/innerText"
android:layout_centerHorizontal="true"
android:onClick="openDialog"/>
</RelativeLayout>
recycler_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="4dp"
android:layout_margin="4dp"
app:cardBackgroundColor="#color/colorCardBack">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#color/colorCard">
<ImageView
android:id="#+id/imageView_1"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="4dp" />
<TextView
android:id="#+id/textview_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text_1"
android:textStyle="bold"
android:textColor="#android:color/black"
android:layout_centerInParent="true"
android:textSize="16sp"
android:layout_marginStart="5dp"
android:layout_toEndOf="#id/imageView_1"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
stats_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="50dp"
android:layout_margin="10dp"
android:background="#color/colorAccent"
android:scrollbars="vertical"
android:layout_above="#id/butClose"/>
<Button
android:id="#+id/butClose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText innerText;
private Button press, butClose;
private ArrayList<RecyclerViewItem> recyclerViewItem;
private ArrayList<String> mainListWord;
private AlertDialog OptionDialog;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerViewItem = new ArrayList<>();
mainListWord = new ArrayList<>();
innerText = findViewById(R.id.innerText);
press = findViewById(R.id.butClose);
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void makeRecyclerList(ArrayList<String> income){
String[] listWord_lenght = income.toArray(new String[0]);
String keyWord = (String.join("", listWord_lenght));
recyclerViewItem.add(new RecyclerViewItem(R.drawable.star, keyWord));
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void openDialog(View v){
String word = innerText.getText().toString();
mainListWord.add(word);
makeRecyclerList(mainListWord);
Dialogus();
innerText.setText("");
}
public void Dialogus(){
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.stats_fragment, null, false);
OptionDialog = new AlertDialog.Builder(this).create();
OptionDialog.setTitle("TestInfo");
recyclerView = v.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(recyclerViewItem);
layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
butClose = v.findViewById(R.id.butClose);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
butClose.setBackgroundColor(Color.CYAN);
butClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OptionDialog.dismiss();
}
});
OptionDialog.show();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewViewHolder> {
private ArrayList<RecyclerViewItem> arrayList;
public static class RecyclerViewViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView_1;
public TextView textview_1;
public RecyclerViewViewHolder(#NonNull View itemView) {
super(itemView);
imageView_1 = itemView.findViewById(R.id.imageView_1);
textview_1 = itemView.findViewById(R.id.textview_1);
}
}
public RecyclerViewAdapter(ArrayList<RecyclerViewItem> arrayList){
this.arrayList = arrayList;
}
#NonNull
#Override
public RecyclerViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_item, viewGroup, false);
RecyclerViewViewHolder recyclerViewViewHolder= new RecyclerViewViewHolder(view);
return recyclerViewViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewViewHolder recyclerViewViewHolder, int position) {
RecyclerViewItem recyclerViewItem = arrayList.get(position);
recyclerViewViewHolder.imageView_1.setImageResource(recyclerViewItem.getImageResource());
recyclerViewViewHolder.textview_1.setText(recyclerViewItem.getText_1());
}
#Override
public int getItemCount() {
return arrayList.size();
}
}
RecyclerViewItem.java
package freijer.app.one;
public class RecyclerViewItem {
private int imageResource;
private String text_1;
public int getImageResource() {
return imageResource;
}
public void setImageResource(int imageResource) {
this.imageResource = imageResource;
}
public String getText_1() {
return text_1;
}
public void setText_1(String text_1) {
this.text_1 = text_1;
}
public RecyclerViewItem(int imageResource, String text_1) {
this.imageResource = imageResource;
this.text_1 = text_1;
}
}

Android View InflateExeption showing up when trying to start an app

I'm new to android development, and I'm having issues with my app crashing when I'm trying to start it
This is the error message:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cybermath/com.example.cybermath.modules.MainActivity}: android.view.InflateException: Binary XML file line #25: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
And this is the XML file for the data within recycler viewer:
'''
<?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="wrap_content"
android:weightSum="100"
android:gravity="center_vertical"
android:background="#color/colorPrimaryDark"
>
<TextView
android:id="#+id/account_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="70"
android:background="#color/colorPrimary"
android:lines="1"
android:padding="10dp"
android:text="#string/app_name"
android:textColor="#color/colorText" >
</TextView>
<TextView
android:id="#+id/account_progress"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="20"
android:background="#color/colorPrimary"
android:text="Enter"
android:textSize="12sp"
android:textColor="#color/colorText"
>
</TextView>
'''
This is the XML for the MainActivity:
<androidx.constraintlayout.widget.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="MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="416dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/informationView"
android:id="#+id/recyclerView">
</androidx.recyclerview.widget.RecyclerView>
<!--<TextView
android:id="#+id/informationView"
android:layout_width="408dp"
android:layout_height="50dp"
android:foregroundTint="#00050000"
android:paddingStart="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:text="Choose an account"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.333"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>-->
</androidx.constraintlayout.widget.ConstraintLayout>
And here is the code for the MainActivity:
'''
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
// UI
private RecyclerView mRecyclerView;
// Variables
#NonNull
private ArrayList<Account> mAccounts = new ArrayList<>();
private AccountsRecyclerAdapter mAccountsRecyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_account_list);
mRecyclerView = findViewById(R.id.recyclerView);
initRecyclerView();
insertFakeAccounts();
}
private void insertFakeAccounts(){
for(int i = 0; i < 1000; i++){
Account account = new Account();
account.setName("title #" + i);
mAccounts.add(account);
}
mAccountsRecyclerAdapter.notifyDataSetChanged();
}
private void initRecyclerView(){
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mAccountsRecyclerAdapter = new AccountsRecyclerAdapter(mAccounts);
mRecyclerView.setAdapter(mAccountsRecyclerAdapter);
}
'''
And my adapter public class AccountsRecyclerAdapter extends
RecyclerView.Adapter<AccountsRecyclerAdapter.ViewHolder> {
private ArrayList<Account> mAccounts = new ArrayList<>();
public AccountsRecyclerAdapter(ArrayList<Account> accounts) {
this.mAccounts = accounts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_account_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AccountsRecyclerAdapter.ViewHolder viewHolder, int i) {
viewHolder.name.setText(mAccounts.get(i).getName());
}
#Override
public int getItemCount() {
return mAccounts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.account_name);
}
}
Some if the thing are not as per requirement may cause an exception. Check for condition as
if(yourValue !=null && yourValue.equals("desired value"){
//do your stuff
}

Recycler View and Card View not displaying cards

This is my Activity:
public String id;
public String passPhrase;
public ArrayList<SongCell> songs;
private RecyclerView recyclerView;
private MyAdapter myAdapter;
private RecyclerView.LayoutManager layoutManager;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songs_view_layout);
Context context = this.getApplicationContext();
Bundle stateData = getIntent().getExtras();
try
{
id = stateData.getString("id");
passPhrase = stateData.getString("passPhrase");
ArrayList data;
recyclerView = (RecyclerView) findViewById(R.id.song_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<SongCell>();
for (int i=0; i<5;i++)
{
data.add(new SongCell("Song "+i,"Artist "+i, null));
}
myAdapter = new MyAdapter(data);
recyclerView.setAdapter(myAdapter);
}
catch(Exception e)
{
Log.d("Error: ", e.toString());
}
}
card.xml
<android.support.v7.widget.CardView android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dp"
>
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/song_photo"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp"
android:background="#drawable/error" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/song_name"
android:textSize="30sp"
android:text="Song Name"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textColor="#000000" />
<ImageButton
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/vote_button"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp"
android:background="#drawable/arrow" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Activity.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:background="#2d2d2d">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="30dp"
android:layout_marginBottom="10dp"
android:background="#222222"></TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingBottom="10dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/featSongImage1"
android:contentDescription="#string/newsongimage"
android:background="#drawable/error" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/songname"
android:id="#+id/featSongName1" />
<ImageButton
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/featSongButt1"
android:background="#drawable/arrow"
android:contentDescription="#string/votearrow" />
</LinearLayout>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foregroundGravity="fill_horizontal"
android:gravity="fill_horizontal|center">
<android.support.v7.widget.RecyclerView
android:id="#+id/song_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal" />
</TableRow>
</TableLayout>
</LinearLayout>
And this is my custom adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
private ArrayList<SongCell> data;
public MyAdapter(ArrayList<SongCell> dataI)
{
data = dataI;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.song_card,viewGroup,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewholder, int pos) {
viewholder.songName.setText(data.get(pos).getName());
viewholder.artist.setText(data.get(pos).getArtist());
viewholder.image.setImageBitmap(data.get(pos).getArtwork());
}
#Override
public int getItemCount() {
return 0;
}
#Override
public int getItemViewType(int position) {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView songName;
TextView artist;
ImageView image;
ImageButton voteButton;
public ViewHolder(View v)
{
super(v);
this.songName = (TextView) v.findViewById(R.id.song_name);
this.image = (ImageView) v.findViewById(R.id.song_photo);
this.voteButton = (ImageButton) v.findViewById(R.id.vote_button);
}
}
}
I have looked at a ton of guides on how to get this working but it still doesn't work. Anyone have any clue what's going on? I'm on version 25.0.1, and have all the modules imported. But it's not adding a single card into the layout.
I thought it would be difficult to debug such a big code you uploaded. But luckily my eye went on this line
#Override
public int getItemCount() {
return 0;
}
return 0; in adapter.
Your list size is always 0.
instead write this
#Override
public int getItemCount() {
return data.size();
}
EDIT-1:
You will also get null pointer exception here
viewholder.artist.setText(data.get(pos).getArtist());
Because you are not initializing the artist variable in ViewHolder class.
Edit-2
#Override
public int getItemCount() {
return 0;
}
you can remove this particular code from your adapter. Because overriding the methods of class that we don't use might sometimes result in errors that you can't even imagine.

BaseAdapter gets me only the first position in ListView Android

I've a major isse with an adapter to show every single row item in a ListView and I only get the first value of the index position.
I've an array of comments from a webservice in android. It's an array inside an array.
The main JSONArray it's "noticias" with has a lot of the previews jsonobject. Now: "comments" it's another array.
This is my ContenidoNews.java class. I pass the "comment" array in a intent from the previews Activity:
public class ContenidoNews extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
private ActionBar bar;
String tituloDetail;
String fullDetail;
String imagenDetail;
String permalink;
String author;
String authorimg;
String dayofmonth;
String month;
String views;
String totalcomments;
String arraycomments;
private SquareImageView mainPic;
private CircularImageView authorpic;
private TextView authors;
private TextView contentTxt;
private ScrollView scollMain;
private TextView mainTxt;
private Animation animSlideDown;
private RelativeLayout relativeAnim;
private RelativeLayout namereceipt;
private Typeface texto;
private Button btnshare;
// Universal Image Loader
private DisplayImageOptions options;
private ImageLoader il = ImageLoader.getInstance();
private DisplayImageOptions opts;
private File cacheDir;
private String imgauthor;
private TextView tvday;
private TextView tvmonth;
private Typeface textofat;
private LinearLayout datestv;
private WebView webview;
private ArrayList links;
private String urlscap;
private String newstring;
private String copyfull;
private String youtube;
private YouTubePlayerView youTubePlayerView;
private String youtubeb;
private String youtubec;
private String youtubed;
private TextView tvtotal;
private TextView tvvisitas;
private String youtubee;
private String youtubef;
private JSONArray arrayComment;
ArrayList<HashMap<String, String>> arrayofcomments;
private ListView listcomment;
private ListAdapter adapter;
private TextView numbcomment;
private TextView tvcomment;
static String AUTHOR = "comauthor";
static String COMMENT = "comtext";
// Grab URLs from text
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contenido);
bar = getActionBar();
bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradiente));
bar.setDisplayHomeAsUpEnabled(true);
bar.setTitle("");
webview = (WebView) findViewById(R.id.wvhit);
webview.getSettings().setJavaScriptEnabled(true);
youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
Intent i = getIntent();
// Get the result of titulo
tituloDetail = i.getStringExtra("titulo").replace("“", "\"").replace("”", "\"").replace("…", "...").replace("–", "-");
// Get the result of full
fullDetail = i.getStringExtra("full");
// Get the result of imagen
imagenDetail = i.getStringExtra("imagen");
// Get the result of permalink
permalink = i.getStringExtra("permalink");
// Get the result of author
author = i.getStringExtra("author");
// Get the result of authorimg
authorimg = i.getStringExtra("authorimg");
int urlimg = authorimg.lastIndexOf("s=128&");
imgauthor = "http://" + authorimg.substring(9, urlimg + 5);
// Get the result of dayofmonth
dayofmonth = i.getStringExtra("dayofmonth");
// Get the result of month
month = i.getStringExtra("month");
// Get the result of views
views = i.getStringExtra("views");
// Get the result of total comments
totalcomments = i.getStringExtra("totalcomments");
// Get the result of array comments
arraycomments = i.getStringExtra("arraycomments");
webview.setWebViewClient(new WebViewClient());
webview.loadUrl(permalink);
pullLinks(fullDetail);
copyfull = fullDetail;
new JSONParser().execute();
texto = Typeface.createFromAsset(this.getAssets(),
"Light.ttf");
textofat = Typeface.createFromAsset(this.getAssets(),
"Bold.ttf");
listcomment = (ListView) findViewById(R.id.listofcomments);
datestv = (LinearLayout) findViewById(R.id.datestv);
tvday = (TextView) findViewById(R.id.tvday);
tvmonth = (TextView) findViewById(R.id.tvmonth);
tvday.setText(dayofmonth);
tvmonth.setText(month);
tvtotal = (TextView) findViewById(R.id.totalvisitas);
tvtotal.setText(views);
tvtotal.setTypeface(textofat);
tvvisitas = (TextView) findViewById(R.id.TVvisitas);
if(views.contentEquals("1")){
tvvisitas.setText("VISITA");
}else{
tvvisitas.setText("VISITAS");
}
tvvisitas.setTypeface(texto);
tvday.setTypeface(textofat);
tvmonth.setTypeface(texto);
mainPic = (SquareImageView) findViewById(R.id.fullimg);
authorpic = (CircularImageView) findViewById(R.id.profile_settings_img);
btnshare = (Button) findViewById(R.id.btnshare);
ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_view);
if (scrollView instanceof Parallaxor) {
((Parallaxor) scrollView).parallaxViewBy(mainPic, 0.6f);
}
relativeAnim = (RelativeLayout) findViewById(R.id.animtext);
animSlideDown = AnimationUtils.loadAnimation(getApplicationContext(),
R.animator.slidetodown);
relativeAnim.startAnimation(animSlideDown);
il.displayImage(imagenDetail, mainPic,opts,new ImageLoadingListener() {
#Override
public void onLoadingStarted(String s, View itemView) {
}
#Override
public void onLoadingFailed(String s, View itemView, FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View itemView, Bitmap bitmap) {
SquareImageView imageView = (SquareImageView) itemView;
if (bitmap != null) {
FadeInBitmapDisplayer.animate(imageView, 500);
}
}
#Override
public void onLoadingCancelled(String s, View view) {
}
});
il.displayImage(imgauthor, authorpic,opts,new ImageLoadingListener() {
#Override
public void onLoadingStarted(String s, View itemView) {
}
#Override
public void onLoadingFailed(String s, View itemView, FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View itemView, Bitmap bitmap) {
CircularImageView imageView = (CircularImageView) itemView;
if (bitmap != null) {
FadeInBitmapDisplayer.animate(imageView, 500);
}
}
#Override
public void onLoadingCancelled(String s, View view) {
}
});
contentTxt = (TextView) findViewById(R.id.textnoti);
if(links.size() != 0 && urlscap.contains("youtu")){
youTubePlayerView.setVisibility(View.VISIBLE);
contentTxt.setText(newstring);
}else{
youTubePlayerView.setVisibility(View.GONE);
contentTxt.setText(fullDetail);
}
authors = (TextView) findViewById(R.id.authors);
authors.setText(author);
authors.setTypeface(texto);
mainTxt = (TextView) findViewById(R.id.tituloreceipt);
mainTxt.setText(tituloDetail);
mainTxt.setTypeface(texto);
namereceipt = (RelativeLayout) findViewById(R.id.namereceipt);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.image);
final Random random = new Random();
//Genrate a random index in the range
int randomInt = random.nextInt(myImages.length());
// Generate the drawableID from the randomInt
int drawableID = myImages.getResourceId(randomInt, -1);
namereceipt.setBackgroundResource(drawableID);
numbcomment = (TextView) findViewById(R.id.numbofcomments);
numbcomment.setText(totalcomments);
tvcomment = (TextView) findViewById(R.id.textforcomments);
if(totalcomments.contentEquals("1")){
tvcomment.setText("COMENTARIO");
}else{
tvcomment.setText("COMENTARIOS");
}
}
My AsyncTask
private class JSONParser extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
arrayofcomments = new ArrayList<HashMap<String, String>>();
arrayComment = new JSONArray(arraycomments);
for(int e = 0; e < arrayComment.length(); e++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject come = arrayComment.getJSONObject(e);
map.put("comauthor", come.getString("comment_author"));
map.put("comtext", come.getString("comment_content"));
arrayofcomments.add(map);
}
} catch (Exception e1) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
adapter = new ListAdapter(getApplicationContext(), arrayofcomments);
listcomment.setAdapter(adapter);
}
}
The result of arrayComment it's:
[
{
"comment_author_url": "http://www.xxxx.com",
"comment_type": "",
"comment_author_IP": "xxxx",
"comment_author": "Mariano xxxx",
"comment_parent": "0",
"comment_agent": "xxxx",
"comment_karma": "0",
"comment_author_email": "xxxx#xxxx.com",
"comment_date": "2014-10-08 17:31:58",
"comment_post_ID": "593",
"comment_ID": "8",
"comment_content": "Prueba",
"user_id": "2",
"comment_date_gmt": "2014-10-08 20:31:58",
"comment_approved": "1"
},
{
"comment_author_url": "",
"comment_type": "",
"comment_author_IP": "xxxx",
"comment_author": "Susana A xxxx",
"comment_parent": "0",
"comment_agent": "xxxx",
"comment_karma": "0",
"comment_author_email": "xxxxxx#yahoo.com.ar",
"comment_date": "2014-10-08 08:28:00",
"comment_post_ID": "593",
"comment_ID": "7",
"comment_content": "una clarísima definición",
"user_id": "0",
"comment_date_gmt": "2014-10-08 11:28:00",
"comment_approved": "1"
}
]
So far so good... now I need to pass all this to my adapter:
public class ListAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private ArrayList<HashMap<String, String>> data;
private HashMap<String, String> resultp;
public ListAdapter(Context context,
ArrayList<HashMap<String, String>> d) {
this.context = context;
data = d;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView author;
TextView comment;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.comment_item, parent, false);
resultp = new HashMap<String, String>();
final int pos = position;
resultp = data.get(position);
Log.e("data", data.get(position).toString());
author = (TextView) itemView.findViewById(R.id.tvauthorcomment);
author.setText(resultp.get(ContenidoNews.AUTHOR));
author.setTypeface(textofat);
comment = (TextView) itemView.findViewById(R.id.tvofcomment);
comment.setText(resultp.get(ContenidoNews.COMMENT));
comment.setTypeface(texto);
return itemView;
}
}
The result of Log.e("data full", data.toString()); its:
10-08 22:33:40.564: E/data full(26463): [{comtext=Prueba, comauthor=Mariano xxxx}, {comtext=una clarísima definición, comauthor=Susana A xxxx}]
Which, by the way, prints 7 times in the log... but it has the 2 values as I need.
Now... this it's what Log.e("data", data.get(position).toString()); gives me:
10-08 22:21:11.444: E/data(24618): {comtext=Prueba, comauthor=Mariano xxxx}
And:
author.setText(resultp.get(ContenidoNews.AUTHOR));
comment.setText(resultp.get(ContenidoNews.COMMENT));
In the adapter also only gave me the first value in my listview (comment_item.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" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvauthorcomment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:paddingLeft="20dp"
android:text="Autor Comentario"
android:textColor="#707070"
android:textSize="20sp" />
<TextView
android:id="#+id/tvofcomment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:paddingLeft="30dp"
android:paddingRight="20dp"
android:text="Contenido del comentario"
android:textColor="#707070"
android:textSize="19sp" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#BBBBBB" />
</LinearLayout>
</LinearLayout>
I can only get the first value... I can't fix this. I'm stock since a lot of hours and nothing. I don't understand what it's the problem. Please, help!
I would thanks any answer in advance!
EDIT: This is my contenido.xml with the scrollview and the listview
<?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/com.renderas.suup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" xmlns:app1="http://schemas.android.com/apk/res/com.mkiisoft.masradio">
<WebView
android:id="#+id/wvhit"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<com.mkiisoft.masradio.utils.SquareImageView
android:id="#+id/fullimg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:scaleType="centerCrop" />
<LinearLayout
android:id="#+id/datestv"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="190dp"
android:background="#90000000" >
<TextView
android:id="#+id/tvday"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:paddingLeft="10dp"
android:text="04"
android:textColor="#FFF"
android:textSize="24sp" />
<TextView
android:id="#+id/tvmonth"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Octubre"
android:textColor="#FFF"
android:textSize="24sp" />
</LinearLayout>
<uk.co.chrisjenx.paralloid.views.ParallaxScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="none" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="240dp" >
<FrameLayout
android:id="#+id/imagecontainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="#+id/namereceipt"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:background="#drawable/bggreenyl" >
<TextView
android:id="#+id/tituloreceipt"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="top|left"
android:paddingBottom="8dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="8dp"
android:text="Noticia Titulo"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFF"
android:textSize="24sp" />
</RelativeLayout>
</FrameLayout>
<RelativeLayout
android:id="#+id/animtext"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/imagecontainer"
android:background="#FFFFFF" >
<com.mkiisoft.masradio.utils.CircularImageView
android:id="#+id/profile_settings_img"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/emptypro" />
<TextView
android:id="#+id/authors"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#id/profile_settings_img"
android:gravity="center_vertical"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#606060"
android:textSize="21sp" />
<LinearLayout
android:id="#+id/linearviews"
android:layout_width="wrap_content"
android:layout_height="22dp"
android:layout_below="#id/authors"
android:layout_marginLeft="15dp"
android:layout_marginTop="8dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imgvisitas"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:layout_marginTop="2dp"
android:alpha="0.7"
android:src="#drawable/eyeviewsblack" />
<TextView
android:id="#+id/totalvisitas"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:gravity="center_vertical"
android:paddingLeft="10dp"
android:text="7"
android:textColor="#606060"
android:textSize="17sp" />
<TextView
android:id="#+id/TVvisitas"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:gravity="center_vertical"
android:paddingLeft="5dp"
android:text="VISITAS"
android:textColor="#606060"
android:textSize="17sp" />
</LinearLayout>
<Button
android:id="#+id/btnshare"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="#id/linearviews"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="12dp"
android:background="#drawable/share_btn"
android:text="COMPARTIR"
android:textColor="#color/checktxt" />
<TextView
android:id="#+id/textnoti"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/btnshare"
android:paddingBottom="20dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="10dp"
android:text="Texto de la noticia"
android:textColor="#707070"
android:textSize="18sp" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/textnoti"
android:layout_marginBottom="20dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="5dp" />
<LinearLayout
android:id="#+id/linearofcomments"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_below="#id/youtubeplayerview"
android:layout_marginLeft="15dp"
android:gravity="center_vertical|left" >
<TextView
android:id="#+id/numbofcomments"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="0"
android:textColor="#707070"
android:textSize="23sp" />
<TextView
android:id="#+id/textforcomments"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginLeft="5dp"
android:text="COMENTARIOS"
android:textColor="#707070"
android:textSize="23sp" />
</LinearLayout>
<ListView
android:id="#+id/listofcomments"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#id/linearofcomments"
android:layout_marginBottom="30dp"
android:layout_marginTop="5dp" >
</ListView>
</RelativeLayout>
</RelativeLayout>
</uk.co.chrisjenx.paralloid.views.ParallaxScrollView>
</RelativeLayout>
We shouldn’t use ListView inside the ScrollView because the list view is already ScrollView, the items in list view are already scrollable..
If you use then the list view will show only one item from the adapter.
Check this post ListView inside scrollview for more details...

Categories

Resources