ViewPager and ListView in its layers - java

I apologize in advance for my terrible English.
My app should have 6 pages, and each of them will have a ListView with its own text.
The list consists of two TextView, so I made my own adapter for it:
BoxAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class BoxAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Kek> objects;
BoxAdapter(Context context, ArrayList<Kek> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// кол-во элементов
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Kek p = getProduct(position);
((TextView) view.findViewById(R.id.textView1)).setText(p.pozic);
((TextView) view.findViewById(R.id.textView1_2)).setText(p.name);
return view;
}
Kek getProduct(int position) {
return ((Kek) getItem(position));
}
}
And auxiliary class for him:
Kek.java
public class Kek {
String name;
String pozic;
Kek(String _pozic,String _describe) {
pozic = _pozic;
name = _describe;
}
}
Next for * * ViewPager* * I also created my adapter:
SlideAdapter.java
package com.github.helpme;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import java.util.List;
public class SlideAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragmentList;
public SlideAdapter (FragmentManager fragmentManager, List<Fragment> fragmentList) {
super(fragmentManager);
this.fragmentList = fragmentList;
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
}
So far I have created 2 test sheets:
Activity_main_1.xml
<?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:orientation="vertical"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView222"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="13dp"
android:layout_marginBottom="15dp"
android:text="НУ РАБОТАЙ ЖЕ ТЫ"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.004" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<ListView
android:id="#+id/lvMain_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:divider="#null"></ListView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
and class
Layout_1.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class Layout_1 extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.activity_main_1, container,false);
return viewGroup;
}
}
On the same analogy created 2nd page:
Activity_main_2.xml
<?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:orientation="vertical"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView222"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="13dp"
android:layout_marginBottom="15dp"
android:text="ЧУХ_ЧУХ"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.004" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<ListView
android:id="#+id/lvMain_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:divider="#null"></ListView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
and class
Layout_2.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class Layout_2 extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.activity_main_2, container,false);
return viewGroup;
}
}
And finally the main activity:
MainActivity.java
package com.github.helpme;
import android.content.Context;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private SlideAdapter slideAdapter;
private ListView lvMain;
private BoxAdapter boxAdapter;
ArrayList<Kek> products = new ArrayList<Kek>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Fragment> list = new ArrayList<>();
list.add(new Layout_1());
list.add(new Layout_2());
viewPager = findViewById(R.id.rader);
slideAdapter = new SlideAdapter(getSupportFragmentManager(),list);
viewPager.setAdapter(slideAdapter);
fillData();
boxAdapter = new BoxAdapter(this, products);
lvMain = (ListView) findViewById(R.id.lvMain_1);
lvMain.setAdapter(boxAdapter);
}
// генерируем данные для адаптера
void fillData() {
for (int i = 1; i <= 20; i++) {
products.add(new Kek (i + ")", "Product " + i));
}
}
}
If you now run the application it will not start, and in the logs you will see:
2019-08-18 09:26:53.879 7138-7138/com.github.helpme E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.github.helpme, PID: 7138
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.github.helpme/com.github.helpme.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2009)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.github.helpme.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:7783)
at android.app.Activity.performCreate(Activity.java:7772)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3235)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
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:2009) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7319) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934) 
When I saw this, I tried to move the loading of the list to the layer classes * * ViewPager**
private ListView lvMain;
private BoxAdapter boxAdapter;
ArrayList<Kek> products = new ArrayList<Kek>();
fillData();
boxAdapter = new BoxAdapter(this, products);
lvMain = (ListView) findViewById(R.id.lvMain_1);
lvMain.setAdapter(boxAdapter);
void fillData() {
for (int i = 1; i <= 20; i++) {
products.add(new Kek (i + ")", "Product " + i));
}
}
But the compiler directly in the code gave an error:
BoxAdapter (android.content.Context, ArrayList) in
BoxAdapter cannot be applied to (com.github.helpme.Layout_1,
ArrayList)
So we got to the essence of this post: How to make Pager sheets with your list inside and how to fill it all.
UDP:
new error:
08-11 15:21:02.956 3653-3653/? E/ActivityThread: Service
com.android.email.service.EmailBroadcastProcessorService has leaked
ServiceConnection com.android.emailcommon.service.am#92c8ab8 that was
originally bound here android.app.ServiceConnectionLeaked: Service
com.android.email.service.EmailBroadcastProcessorService has leaked
ServiceConnection com.android.emailcommon.service.am#92c8ab8 that was
originally bound here at
android.app.LoadedApk$ServiceDispatcher.(LoadedApk.java:1092) at
android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:986) at
android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1303) at
android.app.ContextImpl.bindService(ContextImpl.java:1286) at
android.content.ContextWrapper.bindService(ContextWrapper.java:604) at
com.android.emailcommon.service.ak.a(SourceFile:181) at
com.android.emailcommon.service.ak.e(SourceFile:224) at
com.android.email.service.n.c(SourceFile:177) at
com.android.email.provider.b.a(SourceFile:198) at
com.android.email.provider.b.a(SourceFile:142) at
com.android.email.service.EmailBroadcastProcessorService.c(SourceFile:349)
at
com.android.email.service.EmailBroadcastProcessorService.onHandleIntent(SourceFile:1334)
at
android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
at android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:148) at
android.os.HandlerThread.run(HandlerThread.java:61)

Related

My App crashes after using a Custom Adapter

There is no error showing in the Java file or resources file. This app builds and installs on my device but when I run it, it shows nothing and crashes. What can I do? Here is all of the code and the error message from Logcat when I open the app from my device:
Error Message:
2020-11-13 16:09:33.634 26684-26684/com.example.android.playmanplay E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.playmanplay, PID: 26684
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.android.playmanplay.CustomAdapter.getView(CustomAdapter.java:52)
at android.widget.AbsListView.obtainView(AbsListView.java:2408)
at android.widget.ListView.makeAndAddView(ListView.java:2126)
at android.widget.ListView.fillDown(ListView.java:851)
at android.widget.ListView.fillDown(ListView.java:833)
at android.widget.ListView.fillFromTop(ListView.java:921)
at android.widget.ListView.layoutChildren(ListView.java:1900)
at android.widget.AbsListView.onLayout(AbsListView.java:2204)
at android.view.View.layout(View.java:20699)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1801)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1567)
at android.view.View.layout(View.java:20699)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20699)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at androidx.appcompat.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:446)
at android.view.View.layout(View.java:20699)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20699)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
at android.view.View.layout(View.java:20699)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:757)
at android.view.View.layout(View.java:20699)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2872)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2399)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1534)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7421)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1092)
at android.view.Choreographer.doCallbacks(Choreographer.java:888)
at android.view.Choreographer.doFrame(Choreographer.java:819)
at android.view.Choreographer$FrameHandler.handleMessage(Choreographer.java:991)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
MainActivity.java:
package com.example.android.playmanplay;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ListView listview;
private String[] countryNames;
int[] flags = {R.drawable.afghanistan,R.drawable.bangladesh,R.drawable.bhutan,R.drawable.brazil,R.drawable.canada,
R.drawable.china,R.drawable.denmark,R.drawable.egypt,R.drawable.france,R.drawable.ghana,R.drawable.haiti,
R.drawable.iran,R.drawable.iran,R.drawable.japan,R.drawable.kenya,R.drawable.norway,R.drawable.netherlands,
R.drawable.oman,R.drawable.pakistan,R.drawable.pakistan,R.drawable.russia,R.drawable.slovakia,R.drawable.srilanka,
R.drawable.tajikistan,R.drawable.uzbekistn,R.drawable.wales,R.drawable.zimbabwe};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countryNames = getResources().getStringArray(R.array.name_list);
listview = findViewById(R.id.list_vew);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.text_setter,R.id.text_view,countryNames);
CustomAdapter adapter = new CustomAdapter(this,countryNames,flags);
listview.setAdapter(adapter);
}
}
CustomAdapter.java:
package com.example.android.playmanplay;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class CustomAdapter extends BaseAdapter {
int[]flags;
String[]countryNames;
Context context;
private LayoutInflater inflater;
CustomAdapter(Context context, String[] countryNames,int[] flags){
this.context = context;
this.countryNames = countryNames;
this.flags = flags;
}
#Override
public int getCount() {
return countryNames.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if(convertView == null){
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = this.inflater.inflate(R.layout.text_setter,parent,false);
}
else{
view = convertView;
}
ImageView imageView = convertView.findViewById(R.id.imageview);
TextView textView = convertView.findViewById(R.id.text_view);
imageView.setImageResource(flags[position]);
textView.setText(countryNames[position]);
return (view);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="#3D5AFE"
tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/teal_200"
android:dividerHeight="2dp"
android:id="#+id/list_vew"
/>
</LinearLayout>
text_setter.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:weightSum="4"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/imageview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:contentDescription="#string/flag_of_country"
android:src="#drawable/afghanistan" />
<LinearLayout
android:layout_weight="3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_marginTop="5dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/bangladesh"
android:gravity="center_horizontal"
android:textStyle="bold"
android:id="#+id/text_view" />
<TextView
android:id="#+id/textviewdown"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
You are trying to set size with an appearance:
<TextView
android:id="#+id/textviewdown"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
android:textSize="?android:attr/textAppearanceSmall"/>
This is your view that is throwing an UnsupportedOperationException .
Remove the text size and add android:textAppearance="?android:attr/textAppearanceSmall
#Override
public int getCount() {
return countryNames.size();
}
#Override
public Object getItem(int position) {
return countryNames.get(position);
}
#Override
public long getItemId(int position) {
return countryNames.get(position).getid();
}

Recyclerview (No adapter attached; skipping layout)

i'm just setup my RecyclerView but there's not appear in my emulator & there is error "E/RecyclerView: No adapter attached; skipping layout" Could you guys help me to find my failure?
This is my application layout :
Click here to see my application layout view
StockContent.Java (Fragment) :
package com.example.psmandroidapps;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.Toolbar;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class StockContent extends Fragment {
RecyclerView StockRecyclerView;
List<ModalClass> mList;
CustomAdapter customAdapter;
public StockContent() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View stockview = inflater.inflate(R.layout.stock_content, container, false);
StockRecyclerView = stockview.findViewById(R.id.StockRecyclerView);
customAdapter = new CustomAdapter(mList,getContext());
StockRecyclerView.setAdapter(customAdapter);
StockRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return stockview;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//just for sample only
mList = new ArrayList<>();
mList.add(new ModalClass(R.drawable.profilepicture,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logodetail,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logo,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.profilepicture,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logodetail,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logo,"Mitsubishi S-N50"));
}
}
StockContent.XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3FFFC">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/StockRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
Stock_CardView.XML (for recyclerview content) :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="15dp"
android:layout_margin="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<androidx.cardview.widget.CardView
android:layout_width="100dp"
android:layout_height="100dp"
app:cardCornerRadius="30dp"
android:layout_margin="15dp"
android:layout_weight="0.1">
<ImageView
android:id="#+id/img_goodspicture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/profilepicture"
android:scaleType="centerCrop"/>
</androidx.cardview.widget.CardView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:layout_marginTop="10dp"
android:layout_marginRight="15dp"
>
<TextView
android:id="#+id/txt_goodsname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Mitsubishi S-N10 (220V)"
android:textColor="#000000"
android:fontFamily="#font/sarabun_bold"
android:textSize="21dp"
android:layout_marginBottom="0dp"/>
<TextView
android:id="#+id/txt_goodstype"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Jenis : Contactor"
android:textColor="#000000"
android:fontFamily="#font/sarabun_regular"
android:textSize="12.5dp" />
<TextView
android:id="#+id/txt_goodsstock"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stok : 105 pcs"
android:textColor="#000000"
android:fontFamily="#font/sarabun_regular"
android:textSize="12.5dp"/>
<TextView
android:id="#+id/txt_dateofgoodsentry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Tanggal masuk : 29/07/2020"
android:textColor="#000000"
android:fontFamily="#font/sarabun_regular"
android:textSize="12.5dp"/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
ModalClass.Java :
package com.example.psmandroidapps;
public class ModalClass {
int image;
String text;
public ModalClass(int image, String text) {
this.image = image;
this.text = text;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
CustomAdapter.Java :
package com.example.psmandroidapps;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
List<ModalClass> mList;
Context context;
public CustomAdapter(List<ModalClass> mList, Context context) {
this.mList = mList;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.stock_cardview,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.imageView.setImageResource(mList.get(position).getImage());
holder.textView.setText(mList.get(position).getText());
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.img_goodspicture);
textView=itemView.findViewById(R.id.txt_goodsname);
}
}
}
Thats the code of mine.. the result is nothing, nothing showing in my emulator.. Thank you for read this question, hope you guys can help me to solve my problem here. Thank you guys! have a nice day

Can't get RecyclerView to work [duplicate]

This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 4 years ago.
After being told to use a RecyclerView instead of a ListView, I have tried to implement it along with a SearchView. However, I get a strange error about an object being null:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
I currently have the following code:
SearchActivity.java
package com.rickteuthof.strangejourneycompendium;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.SearchView;
import java.util.ArrayList;
public class SearchActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
public static ArrayList<String> demonNames;
private SearchAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView r = findViewById(R.id.recyclerView);
demonNames = MainActivity.demonNames;
adapter = new SearchAdapter(this, demonNames);
r.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
r.setAdapter(adapter);
SearchView s = findViewById(R.id.searchBar);
s.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return false;
}
}
SearchAdapter.java
package com.rickteuthof.strangejourneycompendium;
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.ArrayList;
import java.util.Locale;
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.MyViewHolder> {
private LayoutInflater inflater;
private ArrayList<String> demonNames;
private ArrayList<String> results;
public SearchAdapter(Context ctx, ArrayList<String> demonNames){
inflater = LayoutInflater.from(ctx);
this.demonNames = demonNames;
this.results = new ArrayList<String>();
this.results.addAll(SearchActivity.demonNames);
}
#NonNull
#Override
public SearchAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.recycler_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SearchAdapter.MyViewHolder holder, int position) {
holder.time.setText(demonNames.get(position));
}
#Override
public int getItemCount() {
return demonNames.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView time;
public MyViewHolder(View itemView) {
super(itemView);
time = itemView.findViewById(R.id.result);
}
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
SearchActivity.demonNames.clear();
if (charText.length() == 0) {
SearchActivity.demonNames.addAll(results);
} else {
for (String wp : results) {
if (wp.toLowerCase(Locale.getDefault()).contains(charText)) {
SearchActivity.demonNames.add(wp);
}
}
}
notifyDataSetChanged();
}
}
My dataset is a String array named demonNames which I try to filter to get the correct results in the RecyclerView.
Here are my xml layouts:
activity_search.xml
<?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=".SearchActivity">
<SearchView
android:id="#+id/searchBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="#+id/recyclerView"
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" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/searchBar" >
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
recycler_item.xml
<?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">
<TextView
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
setContentView(R.layout.activity_main);
Replace this with
setContentView(R.layout.activity_search);

Android: activity is crashed, due to ViewPager Adapter

view pager adapter isn't working, i m posting my code below which i wrote in different files like .java and .xml
kindly resolve the problem. Thanks to the helpers.
package com.example.abbas.exmpression;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.support.v4.view.LayoutInflaterCompat;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class view_pager2 extends PagerAdapter {
private int[] image_resources=
{R.drawable.centre,R.drawable.left,
R.drawable.right,R.drawable.face_guide_center};
private Context ctx;
private LayoutInflater layoutInflater;
public view_pager2(Context ctx){
this.ctx= ctx;
}
#Override
public int getCount() {
return image_resources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view ==(LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater= (LayoutInflater)
ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view =
layoutInflater.inflate(R.layout.activity_third_activity
,container,false);
ImageView imageView = (ImageView)
item_view.findViewById(R.id.cam_images);
TextView textView= (TextView)
item_view.findViewById(R.id.act3_txt2);
imageView.setImageResource(image_resources[position]);
if(position==0)
{
textView.setText("abc");
}
else if(position==1)
{
textView.setText("bla bla ");
}
else if(position==2)
{
textView.setText("ha ha ha ");
}
else
{
textView.setText("akjsdkasjdkl");
}
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object
object) {
container.removeView((LinearLayout)object);
}
}
third_activity.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"
>
<android.support.v4.view.ViewPager
android:id="#+id/screen3"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
</android.support.v4.view.ViewPager>
<TextView
android:id="#+id/act3_txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show us your face, & some moves!"
android:textSize="35sp"
android:textAlignment="center"
android:paddingBottom="20dp"
/>
<ImageView
android:id="#+id/cam_images"
android:layout_height="250sp"
android:layout_width="wrap_content"
android:src="#drawable/centre"
android:layout_below="#+id/act3_txt1"
android:paddingBottom="10dp"
/>
<TextView
android:id="#+id/act3_txt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Align your face & hold to start Recording"
android:layout_below="#+id/cam_images"
android:textSize="35sp"
android:textAlignment="center"
/>
</RelativeLayout>
third_activity.java
so here adapter = new view_pager2(this) is generating a problem which i m not getting what it is. need assistance, please.
public class third_activity extends Activity
{
ViewPager viewPager;
view_pager2 adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(getWindow().FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_third_activity);
viewPager= (ViewPager)findViewById(R.id.screen3);
adapter= new view_pager2(this);
viewPager.setAdapter(adapter);
}
}
Try this,
In your activity
adapter= new view_pager2(third_activity.this);
In your adapter class
Activity ctx;
public view_pager2(Activity ctx){
this.ctx= ctx;
}

StaggeredGrid RecyclerView not showing anything

I'm trying to inflate a RecyclerView which has as StaggeredGrid Layout, but it is not showing anything. I've pretty much copied previous code I've used before for the RecyclerView so I'm kind of stumped.
In MuseumStoriesViewHolder.onCreateViewHolder() the return of holder has the following value ViewHolder{337ec22b position=-1 id=-1, oldPos=-1, pLpos:-1 unboundundefined adapter position no parent} I'm not sure if this is realated, but it was something that seemed off to me.
It also might help to know that the fragment I'm inflating this RecyclerView is a nested Fragment.
Any help would be greatly appreciated.
MuseumFragment
package com.example.android.radiobuttontestproject.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.radiobuttontestproject.R;
import com.example.android.radiobuttontestproject.adapters.MuseumStoriesAdapter;
import com.example.android.radiobuttontestproject.helpers.pojo.StoryObject;
import com.example.android.radiobuttontestproject.test.SampleDataFactory;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MuseumFragment extends Fragment {
private List<StoryObject> storyObjectList;
private StaggeredGridLayoutManager storyGridLayoutManager;
private MuseumStoriesAdapter storyAdapter;
#Bind(R.id.stories_recycler_view) RecyclerView storiesRecyclerView;
public static MuseumFragment newInstance() {
MuseumFragment fragment = new MuseumFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
public MuseumFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_museum, container, false);
ButterKnife.bind(this, view);
//Sets up the stories
SampleDataFactory sampleDataFactory = new SampleDataFactory();
storyObjectList = sampleDataFactory.getSampleStories(
getResources().getStringArray(R.array.test_titles_for_grid_museum1),
getResources().getStringArray(R.array.test_desc_for_grid_museum1));
storyGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
storiesRecyclerView.setLayoutManager(storyGridLayoutManager);
storyAdapter = new MuseumStoriesAdapter(getActivity().getApplicationContext(), storyObjectList);
storiesRecyclerView.setAdapter(storyAdapter);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
MuseumStoriesAdapter
package com.example.android.radiobuttontestproject.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.radiobuttontestproject.R;
import com.example.android.radiobuttontestproject.helpers.pojo.StoryObject;
import java.util.List;
public class MuseumStoriesAdapter extends RecyclerView.Adapter<MuseumStoriesAdapter.MuseumStoriesViewHolder> {
private List<StoryObject> itemList;
private LayoutInflater inflater;
private Context context;
public MuseumStoriesAdapter(Context context, List<StoryObject> itemList) {
this.itemList = itemList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public MuseumStoriesViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = inflater.inflate(R.layout.view_box_small, viewGroup, false);
MuseumStoriesViewHolder holder = new MuseumStoriesViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MuseumStoriesViewHolder holder, int position) {
holder.title.setText(itemList.get(position).getTitle());
holder.desc.setText(itemList.get(position).getDescription());
}
#Override
public int getItemCount() {
return itemList.size();
}
class MuseumStoriesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView type,title,desc;
public MuseumStoriesViewHolder(View itemView) {
super(itemView);
//Tried Butterknife, but it doesn't seem like it was working in the view holder. - Peter
type = (TextView) itemView.findViewById(R.id.small_box_type);
title = (TextView) itemView.findViewById(R.id.small_box_title);
desc = (TextView) itemView.findViewById(R.id.small_box_desc);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked Position = " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
}
fragment_museum.xml
<ScrollView
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="com.example.android.radiobuttontestproject.fragments.MuseumFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<TextView
android:id="#+id/museum_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/header_margin"
android:gravity="center"
android:textSize="#dimen/font_larger"
android:text="#string/museum_header" />
<android.support.v7.widget.RecyclerView
android:id="#+id/stories_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
view_box_small.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/small_box_margin"
android:background="#color/small_box_background_color">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--TODO Make layout_height wrap contenet -->
<ImageView
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#color/test_color2"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:src="#drawable/abc_btn_rating_star_off_mtrl_alpha"
/>
</FrameLayout>
<TextView
android:id="#+id/small_box_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/font_small"
android:textColor="#color/font_red"
android:text="Object"
/>
<TextView
android:id="#+id/small_box_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/font_large"
android:textColor="#color/font_black"
android:text="Sample Text Here"
/>
<TextView
android:id="#+id/small_box_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/font_normal"
android:textColor="#color/font_black"
android:textStyle="italic"
android:text="Sample Text Here"
/>
</LinearLayout>

Categories

Resources