The code does not have any error... But when I run the application on my phone I am getting a null point exception with the recycler view adapter and I do not understand which data is null
I have tried to recreate a layout using the recyclerview adapter but it does not work
RecyclerViewAdapter.java
package com.example.schedule;
/*
* File to help create the recycler view items to be viewed
* Should help with the iteration
* */
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.view.menu.MenuView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import org.w3c.dom.Text;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private ArrayList<String> mScheduleNames = new ArrayList<>();
private ArrayList<String> mScheduleImages = new ArrayList<>();
private Context mContext;
private final String TAG = "RecyclerViewAdapter";
public RecyclerViewAdapter(Context context, ArrayList<String> scheduleNames, ArrayList<String> scheduleImages) {
mScheduleNames = scheduleNames;
mScheduleImages = scheduleImages;
mContext = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.each_element, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d(TAG, "OnBindViewHolder: called.");
Glide.with(mContext)
.load(mScheduleImages.get(position))
.asBitmap()
.into(holder.scheduleImage);
holder.scheduleName.setText(mScheduleImages.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Onclicked: clicked on:" + mScheduleImages.get(position));
Toast.makeText(mContext, mScheduleImages.get(position), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return mScheduleImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
CircleImageView scheduleImage;
TextView scheduleName;
LinearLayout parentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
scheduleImage = itemView.findViewById(R.id.schedule_image);
scheduleName = itemView.findViewById(R.id.schedule_name);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
Layout I want recycled
eachelement.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/parent_layout">
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/schedule_image"
android:layout_width="135dp"
android:layout_height="131dp"
android:src="#drawable/watch"
app:civ_border_color="#FF000000" />
<TextView
android:id="#+id/schedule_name"
android:layout_width="match_parent"
android:layout_height="131dp"
android:layout_weight="1"
android:fontFamily="casual"
android:gravity="center"
android:text="#string/scheduleNames"
android:textSize="18sp"
android:layout_toRightOf="#+id/schedule_image"/>
</RelativeLayout>
Schedules.java
this class should recycle the layout above within the fragment below
package com.example.schedule;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class Schedules extends Fragment {
private static final String TAG = "AddingEvents";
private ArrayList<String> mScheduleNames = new ArrayList<>();
private ArrayList<String> mScheduleImageUrls = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
initImageBitmaps();
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_schedules, container, false);
}
private void initImageBitmaps(){
Log.d(TAG, "initImageBitmaps: preparing image bitmaps.");
mScheduleNames.add("Steve");
mScheduleImageUrls.add("https://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg");
mScheduleNames.add("Bella");
mScheduleImageUrls.add("https://www.crockerriverside.org/sites/main/files/imagecache/square/main-images/camera_lense_0.jpeg");
mScheduleNames.add("Carre");
mScheduleImageUrls.add("https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg/691px-Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg");
initRecyclerView();
}
private void initRecyclerView(){
Log.d(TAG, "initRecyclerView: init recyclerview.");
RecyclerView recyclerView = getView().findViewById(R.id.recyclerviews);
//problem
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity(), mScheduleNames, mScheduleImageUrls);
recyclerView.setAdapter(adapter);
//problem
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
}
fragment_schedules.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=".Schedules"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.constraintlayout.widget.ConstraintLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="113dp"
android:fontFamily="casual"
android:gravity="center"
android:text="#string/Schedules"
android:textSize="18sp"
tools:targetApi="jelly_bean" />
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerviews">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Navigator.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Navigator">
<FrameLayout
android:id="#+id/fragment_area"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom_navigator">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginLeft="9dp"
android:layout_marginRight="9dp"
android:background="#android:color/darker_gray"
android:textAlignment="gravity"
app:menu="#menu/bottom_nav"
android:layout_alignParentBottom="true">
</com.google.android.material.bottomnavigation.BottomNavigationView>
</RelativeLayout>
Navigator.java
This class is supposed to help navigate through the fragments
Schedules is one of the fragments
package com.example.schedule;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class Navigator extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigator);
BottomNavigationView bottom_nav = findViewById(R.id.bottom_navigator);
bottom_nav.setOnNavigationItemSelectedListener(newListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_area,
new Schedules()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener newListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.schedule:
selectedFragment = new Schedules();
break;
case R.id.add:
selectedFragment = new AddingEvents();
break;
case R.id.profile:
selectedFragment = new Profile();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_area,
selectedFragment).commit();
return true;
}
};
}
this is the error I am getting
D/AddingEvents: initImageBitmaps: preparing image bitmaps.
initRecyclerView: init recyclerview.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.schedule, PID: 16701
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.schedule/com.example.schedule.Navigator}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5763)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.schedule.Schedules.initRecyclerView(Schedules.java:60)
at com.example.schedule.Schedules.initImageBitmaps(Schedules.java:55)
at com.example.schedule.Schedules.onCreateView(Schedules.java:38)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2539)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:875)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1227)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1293)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:710)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2063)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1853)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1808)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1715)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2616)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2572)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:525)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:176)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1245)
at android.app.Activity.performStart(Activity.java:6391)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2529)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5763)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
I/System: FinalizerDaemon: finalize objects = 81
I/Process: Sending signal. PID: 16701 SIG: 9
Application terminated.
I expect a recycled schedule with the provided details
In Schedules.java with the initBitmaps() method
I think the issue is because I am using fragments but I want the recycle
to happen there not within the activity
Change to this
public class Schedules extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater . inflate (R.layout.fragment_schedules, container, false);
initImageBitmaps();
RecyclerView recyclerView = view.findViewById (R.id.recyclerviews);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity(), mScheduleNames, mScheduleImageUrls);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager (getActivity()));
return view;
}
}
Related
I'm trying to show all the card views using recycler view in main activity. Although I did not set a huge margin between card views, my recycler view shows a huge space to print the next card view. please see my attached image, you'll understand what I'm trying to say. I've attached all the code here. Can you please advise how to solve this problem? Thank you.
<?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">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
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.0"
tools:listitem="#layout/note_card" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="50dp"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="#+id/recyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="#drawable/add" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_margin="7dp"
app:cardBackgroundColor="#color/green"
app:cardCornerRadius="5dp"
app:cardElevation="5dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textViewTitleCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="TextView"
android:textSize="20sp" />
<TextView
android:id="#+id/textViewDescriptionCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginTop="16dp"
android:text="TextView"
android:textSize="16sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
package com.destructivepaul.quicknote;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteHolder>{
private List<MyNote> myNoteList = new ArrayList<>();
// private Context context;
public void setMyNoteList(List<MyNote> myNoteList) {
this.myNoteList = myNoteList;
notifyDataSetChanged();
Log.i("info","note updated on adapter. note list size: "+myNoteList.size());
}
//public void setContext(Context context) {
// this.context = context;
// notifyDataSetChanged();
// Log.i("info","context updated on adapter");
// }
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.note_card
,parent,false);
return new NoteHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NoteHolder holder, int position) {
MyNote myNote=myNoteList.get(position);
holder.textViewTitle.setText(myNote.getNote_title());
holder.textViewDescription.setText(myNote.getNote_description());
}
#Override
public int getItemCount() {
return myNoteList.size();
}
public class NoteHolder extends RecyclerView.ViewHolder{
private TextView textViewTitle, textViewDescription;
private CardView cardView;
public NoteHolder(#NonNull View itemView) {
super(itemView);
textViewTitle=itemView.findViewById(R.id.textViewTitleCard);
textViewDescription=itemView.findViewById(R.id.textViewDescriptionCard);
cardView=itemView.findViewById(R.id.cardView);
Log.i("info","card design found on adapter");
}
}
}
package com.destructivepaul.quicknote;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private FloatingActionButton fab;
private RecyclerView recyclerView;
private MyNoteViewModel myNoteViewModel;
private ActivityResultLauncher<Intent> activityResultLauncherForAddNote;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//resisterActivity
resisterActivityForAddNote();
fab=findViewById(R.id.fab);
recyclerView=findViewById(R.id.recyclerView);
NoteAdapter adapter=new NoteAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
Log.i("info","set the adapter");
myNoteViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication())
.create(MyNoteViewModel.class);
myNoteViewModel.getAllNotes().observe(MainActivity.this, new Observer<List<MyNote>>() {
#Override
public void onChanged(List<MyNote> myNotes) {
adapter.setMyNoteList(myNotes);
Log.i("info","adapter is called to update data");
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(MainActivity.this,CreateNoteActivity.class);
//resister activity launcher
activityResultLauncherForAddNote.launch(intent);
Log.i("info","called resister activity launcher on fab");
}
});
}
public void resisterActivityForAddNote(){
activityResultLauncherForAddNote=registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
int resultCode=result.getResultCode();
Intent data = result.getData();
if (resultCode==RESULT_OK && data !=null) {
String title = data.getStringExtra("title");
String description = data.getStringExtra("description");
String colorName = data.getStringExtra("color");
MyNote myNote = new MyNote(title, description, colorName);
Log.i("info", "new note created on activity result");
myNoteViewModel.insert(myNote);
Log.i("info", "note saved to database");
}
}
});
}
}
I've solved my problem by myself. The problem was on card layout design(parent layout height should be wrap content instead of match parent).
I am Using a Tab Layout with two fragments both have Recycler View and also added Search View in Tab Layout but here I am facing a problem, I want Search View to work on Both Fragment that I added As Tab but Search View is in another activity(Toolbar) and both fragments are different
Activity Having Tabs(LanguageChooser Activity)
package com.piyushjaiswal.lyricswala;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.material.tabs.TabLayout;
public class LanguageChooser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_language_chooser);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SectionPagerAdapter pagerAdapter = new SectionPagerAdapter(getSupportFragmentManager(),FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
ViewPager pager = findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(pager);
}
private class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(#NonNull FragmentManager fm, int behaviour) {
super(fm,behaviour);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new Hindi();
case 1:
return new Punjabi();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0: return getResources().getText(R.string.Hindi);
case 1:return getResources().getText(R.string.Punjabi);
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.toolbar,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
System.exit(1);
}
}
XML CODE OF LanguageChooserActivity
<?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:orientation="vertical"
tools:context=".LanguageChooser">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="#+id/toolbar"
android:background="#color/colorAccent"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
app:elevation="0dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabs"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:id="#+id/pager"
android:layout_height="match_parent" />
</LinearLayout>
My Toolbar having Search View
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_Search"
android:title="#string/search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.widget.SearchView"
/>
</menu>
XML code of first Tab(Fragment) named as Hindi
<?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:orientation="vertical"
tools:context=".Hindi">
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/progressbar"
android:visibility="visible"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
Java Code of Tab(Fragment) named as Hindi
package com.piyushjaiswal.lyricswala;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.app.SearchManager;
import android.widget.ProgressBar;
import androidx.appcompat.widget.SearchView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class Hindi extends Fragment {
View v;
private RecyclerView myRecyclerview;
private List<Contact> listContact = new ArrayList<>();
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference myRef = database.getReference();
private RecyclerViewAdapter recyclerViewAdapter;
private ProgressBar progressBar;
public Hindi() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_hindi,container,false);
progressBar= v.findViewById(R.id.progressbar);
progressBar.setVisibility(View.VISIBLE);
myRecyclerview = v.findViewById(R.id.recyclerView);
myRecyclerview.setHasFixedSize(true);
myRecyclerview.setItemViewCacheSize(10);
recyclerViewAdapter = new RecyclerViewAdapter(getContext(),listContact);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
myRecyclerview.setLayoutManager(layoutManager);
myRecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myRef.child("Hindi").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
listContact.add(dataSnapshot1.getValue(Contact.class));
}
recyclerViewAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
Recycler View Adapter
package com.piyushjaiswal.lyricswala;
import android.content.Context;
import android.content.Intent;
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 com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Context mContext;
private List<Contact> mData;
private List<Contact> mDataFull;
public RecyclerViewAdapter(Context mContext, List<Contact> mData) {
this.mContext = mContext;
this.mData = mData;
mDataFull = new ArrayList<>(mData);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_songs,parent,false);
MyViewHolder vHolder= new MyViewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.setData(mData.get(position).getName(),mData.get(position).getPhone(),mData.get(position).getUrl(),mData.get(position).getLyrics());
}
#Override
public int getItemCount() {
return mData.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder
{
private TextView tv_name;
private TextView tv_phone;
private ImageView imageView;
MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_name = (TextView) itemView.findViewById(R.id.name_contact);
tv_phone = (TextView) itemView.findViewById(R.id.phone_contact);
imageView = (ImageView) itemView.findViewById(R.id.img_contact);
}
private void setData(final String name, final String phone, String url, final String Lyrics){
Glide.with(itemView.getContext()).load(url).into(imageView);
this.tv_phone.setText(phone);
this.tv_name.setText(name);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(itemView.getContext(),LyricsActivit.class);
intent.putExtra("Lyrics",Lyrics);
intent.putExtra("albumname",phone);
intent.putExtra("songname",name);
itemView.getContext().startActivity(intent);
}
});
}
}
}
Screen Shot of My ActivityApp Output
I want above toolbar search view to work on tabs(fragment) Hope I explain my problem
Create a view pager and tab layout together. it will be resolved.Here is an example.
I have the following code which is a fragment that has a recycler view and I have an adapter, debugging my code shows that the adapter is getting called after the fragment returns the result, although I am creating an instance of the adapter and setting it to the recycler view and setting the wanted results before returning the fragment. can someone help explaining what's happening I am new to Android with a bit of java experience.
Here is my fragment class:
package com.clowiz.ui.gallery;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.clowiz.MainActivity;
import com.clowiz.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
import static android.app.Activity.RESULT_OK;
public class GalleryFragment extends Fragment {
public static final int ADD_UNIVERSITY_CODE = 1;
private GalleryViewModel galleryViewModel;
private UniversityViewModel universityViewModel;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_gallery, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
FloatingActionButton buttonAddUniversity = view.findViewById(R.id.button_add_university);
buttonAddUniversity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), AddUniversityActivity.class);
startActivityForResult(intent, ADD_UNIVERSITY_CODE);
}
});
RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
final UniversityAdapter adapter = new UniversityAdapter();
recyclerView.setAdapter(adapter);
universityViewModel = ViewModelProviders.of(this).get(UniversityViewModel.class);
universityViewModel.getAllUniversities().observe(this, new Observer<List<University>>() {
#Override
public void onChanged(#Nullable List<University> unis) {
adapter.setUniversities(unis);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ADD_UNIVERSITY_CODE && resultCode == RESULT_OK) {
String name = data.getStringExtra(AddUniversityActivity.EXTRA_NAME);
University uni = new University(name);
universityViewModel.insert(uni);
Toast.makeText(getContext(), "uni added successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "uni not saved", Toast.LENGTH_SHORT).show();
}
}
}
Here is my adapter:
package com.clowiz.ui.gallery;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.clowiz.R;
import java.util.ArrayList;
import java.util.List;
public class UniversityAdapter extends RecyclerView.Adapter<UniversityAdapter.UniversityHolder> {
private List<University> universities = new ArrayList<>();
#NonNull
#Override
public UniversityHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.university_item, parent, false);
return new UniversityHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull UniversityHolder holder, int position) {
University university = universities.get(position);
holder.textViewId.setText(String.valueOf(university.getId()));
holder.textViewName.setText(university.getName());
}
#Override
public int getItemCount() {
return universities.size();
}
public void setUniversities(List<University> universities) {
this.universities = universities;
notifyDataSetChanged();
}
class UniversityHolder extends RecyclerView.ViewHolder {
private TextView textViewId;
private TextView textViewName;
public UniversityHolder(View itemView) {
super(itemView);
textViewId = itemView.findViewById(R.id.text_view_id);
textViewName = itemView.findViewById(R.id.text_view_name);
}
}
}
Here is my viewModel:
package com.clowiz.ui.gallery;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class UniversityViewModel extends AndroidViewModel {
private UniversityRepository repository;
private LiveData<List<University>> allUniversities;
public UniversityViewModel(#NonNull Application application) {
super(application);
repository = new UniversityRepository(application);
allUniversities = repository.getAllUniversities();
}
public void insert(University university) {
repository.insert(university);
}
public void update(University university) {
repository.update(university);
}
public void delete(University university) {
repository.delete(university);
}
public LiveData<List<University>> getAllUniversities() {
return allUniversities;
}
}
Here is my listItem:
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.023">
<TextView
android:id="#+id/text_view_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="Id"
android:textAppearance="#style/TextAppearance.AppCompat.Large"></TextView>
<TextView
android:id="#+id/text_view_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_toStartOf="#id/text_view_id"
android:layout_toLeftOf="#id/text_view_id"
android:text="Name"
android:textAppearance="#style/TextAppearance.AppCompat.Large"></TextView>
</RelativeLayout>
</LinearLayout>
Here is my fragment view:
<?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">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="159dp"
tools:layout_editor_absoluteY="182dp"
tools:listitem="#layout/university_item">
</androidx.recyclerview.widget.RecyclerView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/button_add_university"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:src="#drawable/ic_add_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.21"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.916" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is my repository:
package com.clowiz.ui.gallery;
public class UniversityViewModel extends AndroidViewModel {
private UniversityRepository repository;
private LiveData<List<University>> allUniversities;
public UniversityViewModel(#NonNull Application application) {
super(application);
repository = new UniversityRepository(application);
allUniversities = repository.getAllUniversities();
}
public void insert(University university) {
repository.insert(university);
}
public void update(University university) {
repository.update(university);
}
public void delete(University university) {
repository.delete(university);
}
public LiveData<List<University>> getAllUniversities() {
return allUniversities;
}
}
If you want to have the correct design around this, you should move all that code to onViewCreated instead and keep onCreateView as simple as:
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_gallery, container, false);
}
Edit: Also, provide a LayoutManager to the RecyclerView as I've missed that on my initial read.
And then you can use the view instance of onViewCreated to get your other views.
your problem is that once you open a fragment, a list of uni's is displayed by default. when you click on add a new uni using the floating button, you go to 'AddUniversityActivity' and expect when you get back to see the new one added with no duplicates or weird behaviour.
here is what I think you should do :
1) override|impelment hashcode on the class University to make each instance unique ( maybe use university id ).
2) use HashSet as a collection for your universities instead of List.
since you are learning, take a look at observable design pattern , activity lifecycle , fragmnet lifecycle .
I want to add Recyclerview inside fragment then after that want to add fragment inside viewpager.So i follow tutorial on youtube.after compile..recyclerview is display but when i go to next tabs,exception appear.Hope you guys can help me solve this problem.
ERROR
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.recyclerviewpagerfragment, PID: 3705
java.lang.ClassCastException: android.support.v7.widget.LinearLayoutCompat cannot be cast to android.support.v7.widget.RecyclerView
at com.example.user.recyclerviewpagerfragment.Fragments.DocumentaryFragment.onCreateView(DocumentaryFragment.java:30)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1240)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1088)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:275)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I/Process: Sending signal. PID: 3705 SIG: 9
Application terminated.
MainActivity.java
package com.example.user.recyclerviewpagerfragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.example.user.recyclerviewpagerfragment.Fragments.CrimeFragment;
import com.example.user.recyclerviewpagerfragment.Fragments.DocumentaryFragment;
import com.example.user.recyclerviewpagerfragment.Fragments.DramaFragment;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//initialize view pager.
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager_id);
this.addPages(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_id);
//it gonna occupy the whole screen..
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(listener(viewPager));
}
// add all pages
private void addPages(ViewPager pager){
FragPagerAdapter adapter = new FragPagerAdapter(getSupportFragmentManager());
adapter.addPage(new CrimeFragment());
adapter.addPage(new DramaFragment());
adapter.addPage(new DocumentaryFragment());
//set adapter to pager
pager.setAdapter(adapter);
}
private TabLayout.OnTabSelectedListener listener(final ViewPager pager){
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
}
FragPagerAdapter.java
package com.example.user.recyclerviewpagerfragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* Created by User on 10/4/2016.
*/
public class FragPagerAdapter extends FragmentPagerAdapter{
//create arraylist..where its gonna hol fragment.
ArrayList<Fragment> pages = new ArrayList<>();
public FragPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return pages.get(position);
}
#Override
public int getCount() {
return pages.size();
}
// add a page
public void addPage(Fragment f){
pages.add(f);
}
//set title for tab
#Override
public CharSequence getPageTitle(int position) {
return pages.get(position).toString();
//return super.getPageTitle(position);
}
}
MyRecyclerAdapter.java
package com.example.user.recyclerviewpagerfragment.Recycler;
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.Toast;
import com.example.user.recyclerviewpagerfragment.R;
import java.util.ArrayList;
/**
* Created by User on 10/4/2016.
*/
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyViewHolder> {
Context context;
ArrayList<Movie> movies;
public MyRecyclerAdapter(Context context, ArrayList<Movie> movies) {
this.context = context;
this.movies = movies;
}
//initialize holder.
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
MyViewHolder holder = new MyViewHolder(view);
return holder;
//return null;
}
//bind data to views
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.nameTxt.setText(movies.get(position).getImage());
holder.img.setImageResource(movies.get(position).getImage());
//listener
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(context,movies.get(position).getName(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return movies.size();
}
}
MyViewHolder.java
package com.example.user.recyclerviewpagerfragment.Recycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.user.recyclerviewpagerfragment.R;
/**
* Created by User on 10/4/2016.
*/
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView img;
TextView nameTxt;
ItemClickListener itemClickListener;
public MyViewHolder(View itemView) {
super(itemView);
nameTxt = (TextView) itemView.findViewById(R.id.nameTxt);
img = (ImageView) itemView.findViewById(R.id.movieImage);
//above...if want to make click on nameTxt,can change itemView to nameTxt
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener){
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
this.itemClickListener.onItemClick(view,getLayoutPosition());
}
}
DocumentaryFragment.java
package com.example.user.recyclerviewpagerfragment.Fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.user.recyclerviewpagerfragment.R;
import com.example.user.recyclerviewpagerfragment.Recycler.Movie;
import com.example.user.recyclerviewpagerfragment.Recycler.MyRecyclerAdapter;
import java.util.ArrayList;
/**
* Created by User on 10/4/2016.
*/
public class DocumentaryFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//call view
View view = inflater.inflate(R.layout.documentary_fragment,null);
//recyclerview
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.mRecyclerDocumentary);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
//set Adapter
recyclerView.setAdapter(new MyRecyclerAdapter(this.getActivity(),getDocumentaryMovies()));
return view;
//return super.onCreateView(inflater, container, savedInstanceState);
}
private ArrayList<Movie> getDocumentaryMovies() {
//collection of crime movies.
ArrayList<Movie> movies = new ArrayList<>();
//single movie
Movie movie = new Movie("Crime:tank5",R.drawable.e);
//add to collection..
movies.add(movie);
movie = new Movie("Crime:tank6",R.drawable.f);
movies.add(movie);
return movies;
/*
Movie movie = new Movie("tank1",R.drawable.a);
movies.add(movie);
Movie movie = new Movie("tank1",R.drawable.a);
movies.add(movie);
*/
}
//set title for the fragment
#Override
public String toString() {
return "Documentary";
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
android:fitsSystemWindows="true"
tools:context="com.example.user.recyclerviewpagerfragment.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<!-- add above for adding tablayout -->
<android.support.design.widget.TabLayout
android:id="#+id/tab_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
<!-- add above for adding viewpager -->
<android.support.v4.view.ViewPager
android:id="#+id/viewpager_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Documentary_fragment.xml
<android.support.v7.widget.LinearLayoutCompat
android:id="#+id/mRecyclerDocumentary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></android.support.v7.widget.LinearLayoutCompat> </LinearLayout>
Model.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="10dp"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/movieImage"
android:padding="10dp"
android:src="#drawable/a"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name"
android:id="#+id/nameTxt"
android:padding="10dp"
android:textColor="#color/colorAccent"
android:layout_below="#+id/movieImage"
android:layout_alignParentLeft="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="this tanks is awsome no need to jurge it."
android:id="#+id/descTxt"
android:layout_below="#+id/nameTxt"
android:layout_alignParentLeft="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="TV Show"
android:id="#+id/posTxt"
android:padding="10dp"
android:layout_below="#id/movieImage"
android:layout_alignParentRight="true"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chk"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
the error is
java.lang.ClassCastException: android.support.v7.widget.LinearLayoutCompat cannot be cast to android.support.v7.widget.RecyclerView
at com.example.user.recyclerviewpagerfragment.Fragments.DocumentaryFragment.onCreateView(DocumentaryFragment.java:30)
As it says the problem is in DocumentaryFragment, you are casting a LinearLayout to a ReciclerView, you should provide us that Fragment.
Hope it helps, I would like to comment but I do not have the requisites yet.
after 2 hours of watching tutorial on RecyclerView I just stuck on the blank Screen. I just want that my code runs and I get the required Output. Also I need some information about cardView. Any help would be appreciated.
here is my code
Adapter.java
package bhanu13.flyourskills;
import android.content.Context;
import android.media.Image;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private final LayoutInflater inflator;
List<RowContent> data= Collections.emptyList();
public Adapter(Context context,List<RowContent> data) {
this.data=data;
inflator=LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflator.inflate(R.layout.one_row,parent,false);
MyViewHolder myViewHolder=new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.firstImageButton.setBackgroundResource(R.drawable.himi);
holder.secondImageButton.setBackgroundResource(R.drawable.himi);
holder.textView.setText("A");
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder
{
ImageButton firstImageButton;
ImageButton secondImageButton;
TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
firstImageButton= (ImageButton) itemView.findViewById(R.id.first_image_button);
secondImageButton= (ImageButton) itemView.findViewById(R.id.second_image_button);
textView= (TextView) itemView.findViewById(R.id.textview);
}
}
}
Fregment's code
package bhanu13.flyourskills;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
public class ButtonsFregment extends Fragment {
RecyclerView recyclerView;
Adapter adapter;
ImageButton firstImageButton;
ImageButton secondImageButton;
Context context;
private List<RowContent> data;
public ButtonsFregment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_buttons_fregment, container, false);
recyclerView= (RecyclerView) view.findViewById(R.id.recycler_view);
adapter=new Adapter(getActivity(),getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public List<RowContent> getData() {
List<RowContent> rowContents=new ArrayList<>();
RowContent rowContent=new RowContent();
rowContent.firstImageID=R.drawable.himi;
rowContent.secondImageID=R.drawable.himi;
rowContents.add(rowContent);
return rowContents;
}
}
One_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/first_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/second_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dummy"
android:id="#+id/textview"/>
</LinearLayout>
and Fragment's 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"
tools:context=".ButtonsFregment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
MainActivity.java
package bhanu13.flyourskills;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
for (int i = 0; i < 4; i++) {
Fragment buttonsFragment = new ButtonsFregment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.linear_fragments, buttonsFragment).commit();
}
}
}
Activity
package com.example.usmank.myapplication;
import android.app.ProgressDialog;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressDialog pd=new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
pd.show();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.framLayout,new YourFragment());
fragmentTransaction.commit();
if(pd.isShowing()) {
pd.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
fragment
package com.example.usmank.myapplication;
/**
* Created by usmank on 3/8/2016.
*/
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
public class YourFragment extends Fragment {
RecyclerView recyclerView;
Adapter adapter;
ImageButton firstImageButton;
ImageButton secondImageButton;
Context context;
public YourFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_buttons_fragment, container, false);
recyclerView= (RecyclerView) view.findViewById(R.id.recycler_view);
adapter=new Adapter(getActivity());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
}
adapter
package com.example.usmank.myapplication;
/**
* Created by usmank on 3/8/2016.
*/
import android.content.Context;
import android.media.Image;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private final LayoutInflater inflator;
public Adapter(Context context) {
inflator=LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflator.inflate(R.layout.one_row,parent,false);
MyViewHolder myViewHolder=new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.firstImageButton.setBackgroundResource(R.mipmap.ic_launcher);
holder.secondImageButton.setBackgroundResource(R.mipmap.ic_launcher);
holder.textView.setText("A");
}
#Override
public int getItemCount() {
//data.size()
return 10;
}
class MyViewHolder extends RecyclerView.ViewHolder
{
ImageButton firstImageButton;
ImageButton secondImageButton;
TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
firstImageButton= (ImageButton) itemView.findViewById(R.id.first_image_button);
secondImageButton= (ImageButton) itemView.findViewById(R.id.second_image_button);
textView= (TextView) itemView.findViewById(R.id.textview);
}
}
}
fragment 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"
tools:context=".ButtonsFregment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
recycler xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/first_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/second_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dummy"
android:id="#+id/textview"/>
</LinearLayout>
activty 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=".MainActivity">
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/framLayout">
</FrameLayout>
</RelativeLayout>
gredle file
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.example.usmank.myapplication"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.android.support:recyclerview-v7:23.1.1'
}
I am using like this it is working perfectly please change according to your requirments
Recycler Adapter is
package adapter;
import android.app.Activity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.maps.model.LatLng;
import com.mycompany.locationsharing.R;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import common.CommUtil;
import common.SendNotifications;
/**
* Created by usmank on 1/15/2016.
*/
public class FriendsListsAdapter extends RecyclerView.Adapter<FriendsListsAdapter.ViewHolder> {
private final Activity activity;
private final JSONArray arrayFriendList;
private static final String TAG="MY_FRIEND_ID";
private FragmentTransaction fragmentTransaction;
private LatLng mLatLng;
public FriendsListsAdapter(Activity activity, JSONArray arrayFriendList,LatLng mLatLng) {
this.activity = activity;
this.arrayFriendList = arrayFriendList;
this.mLatLng = mLatLng;
}
static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView friendsName;
private final ImageView ivFriendImage;
public ViewHolder(View v) {
super(v);
friendsName = (TextView) v.findViewById(R.id.tvFriendsName);
ivFriendImage= (ImageView) v.findViewById(R.id.ivFriendsImage);
v.setClickable(true);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
View view = layoutInflater.inflate(R.layout.recycler_item, viewGroup, false);
ViewHolder vh = new ViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
try {
viewHolder.friendsName.setText(arrayFriendList.getJSONObject(i).get("name").toString());
Picasso.with(activity).load("https://graph.facebook.com/"+ arrayFriendList.getJSONObject(i).get("id").toString()+"/picture")
.placeholder(R.drawable.placeholder).resize(160, 170).into(viewHolder.ivFriendImage);
CommUtil.showDebugLogs(TAG,arrayFriendList.getJSONObject(i).get("id").toString());
} catch (JSONException e) {
CommUtil.showExceptionTrace(e);
}
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
SendNotifications sendNotifications = new SendNotifications(activity,arrayFriendList.getJSONObject(i).get("name").toString());
String[] parems = {arrayFriendList.getJSONObject(i).get("id").toString(),String.valueOf(mLatLng.latitude),String.valueOf(mLatLng.longitude)};
sendNotifications.execute(parems);
} catch (JSONException e) {
CommUtil.showExceptionTrace(e);
}
}
});
}
#Override
public int getItemCount() {
return arrayFriendList.length();
}
#Override
public int getItemViewType(int position) {
return position;
}
}
and where i am using this
recyclerFriendList.setAdapter(new FriendsListsAdapter(getActivity(), friendsJsonArray,new LatLng(latitude,longitude)));
and recycler_item.xml is
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_margin="5dp"
android:elevation="4dp"
card_view:cardUseCompatPadding="true"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="10dp"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#mipmap/ic_launcher"
android:paddingRight="7dp"
android:id="#+id/ivFriendsImage"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/tvFriendsName"
android:text="Hello My Friend"
android:textColor="#000"
xmlns:android="http://schemas.android.com/apk/res/android" />
</LinearLayout>
</android.support.v7.widget.CardView>
and where recycler view is used
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerFriendsList"
android:background="#e7e7e7"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</android.support.v7.widget.RecyclerView>
and please also in import recycler library
and carview is also used in it which is the component of material design which can be used to beautify