Fragment holding a RecyclerView not showing in the MainActivity - java

I'm trying to show a RecyclerView, in a fragment, in my main activity.
I'm not getting any errors, but the fragment remains empty, and I can't find the solution for this problem.
I simply have a fragment that has a recyclerview in it, I configure the recyclerview in HomeFragment.java, then in the MainParkActivity, I have a FrameLayout, which is replaced with the HomeFragment.
MainParkActivity
package com.example.ipark;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;;
public class MainParkActivity extends AppCompatActivity {
private static final String TAG = "MainParkActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: started.");
Toolbar toolbar = findViewById(R.id.toolbar);
Fragment homeFragment = new HomeFragment();
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("iParc");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, homeFragment).commit();
}
}
HomeFragment
package com.example.ipark;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private static final String TAG = "HomeFragment";
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
giveInformation();
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), mNames, mImageUrls);
recyclerView.setAdapter(adapter);
}
private void giveInformation() {
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("BMW");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Audi");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Hyundai");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Mercedes");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("BMW");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Audi");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Hyundai");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Mercedes");
}
}
RecyclerViewAdapter
package com.example.ipark;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> mImageNames;
private ArrayList<String> mImages;
private Context mContext;
public RecyclerViewAdapter(Context mContext, ArrayList<String> mImageNames, ArrayList<String> mImages) {
this.mImageNames = mImageNames;
this.mImages = mImages;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
ViewHolder holder;
holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(mContext)
.asBitmap()
.load(mImages.get(position))
.into(holder.image);
holder.imageName.setText(mImageNames.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on: " + mImageNames.get(position));
Toast.makeText(mContext, mImageNames.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mImageNames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
TextView imageName;
RelativeLayout parentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
imageName = itemView.findViewById(R.id.image_name);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
}
XML for activity_main
<?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=".MainParkActivity"
android:clipToPadding="false">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
XML for fragment_home
<?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">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

In your fragment_home.xml, your Recyclerview has layout_height and layout_width 0dp. Change it to match_parent. Everything else in your code is correct. I'd have commented it, but I currently do not have commenting privileges! Accept it if you found it helpful!

In your activity_main layout, you have app:layout_constraintBottom_toTopOf="parent"
It should be app:layout_constraintBottom_toBottomOf="parent"
Your layout is currently displaying above the screen in your fragment.

use
adapter.notifyDataSetChanged();
after setting the adapter for RecycleView.

Related

Getting all launchable apps on home like android home menu with bottom dots

Hi i am working on a custom launcher app.I want to get all launchable apps on home like this.
My Current Code:
MainActivity.class
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycalview);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
StaggeredGridLayoutManager mGridLayoutManager = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL); // 2 is number of items per row
recyclerView.setLayoutManager(mGridLayoutManager); // deafult
PackageManager pm = this.getPackageManager();
Intent main = new Intent(Intent.ACTION_MAIN, null);
main.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> launchables = pm.queryIntentActivities(main, 0);
Collections.sort(launchables,
new ResolveInfo.DisplayNameComparator(pm));
Adapter adapter = new Adapter(this, launchables, pm);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(mGridLayoutManager);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycalview"
android:layout_below="#+id/battery"
android:layout_width="match_parent"
android:layout_above="#id/hi"
android:layout_height="match_parent" />
</RelativeLayout>
Adapter.java
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
List<ResolveInfo> lapps;
Context context;
PackageManager pm=null;
public Adapter(Context context, List<ResolveInfo> apps, PackageManager pn) {
this.context = context;
lapps=apps;
pm=pn;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.griditem, parent, false);
Adapter.ViewHolder viewHolder = new Adapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull Adapter.ViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.images.setImageDrawable(lapps.get(position).loadIcon(pm));
holder.text.setText(lapps.get(position).loadLabel(pm));
holder.itemlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ResolveInfo launchable = lapps.get(position);
ActivityInfo activity = launchable.activityInfo;
ComponentName name = new ComponentName(activity.applicationInfo.packageName,
activity.name);
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
i.setComponent(name);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return lapps.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView images;
TextView text;
RelativeLayout itemlayout;
public ViewHolder(View view) {
super(view);
images = (ImageView) view.findViewById(R.id.icon);
text = (TextView) view.findViewById(R.id.label);
itemlayout=view.findViewById(R.id.item);
}
}
}
griditem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/item"
android:layout_marginTop="5dp"
android:gravity="center"
android:layout_height="wrap_content">
<com.google.android.material.imageview.ShapeableImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/icon"
android:theme="#style/Theme.RoundedImage"/>
<TextView
android:layout_width="60dp"
android:layout_height="20dp"
android:layout_marginTop="5dp"
android:layout_below="#id/icon"
android:gravity="center_horizontal"
android:textSize="15dp"
android:textColor="#color/white"
android:textStyle="bold"
android:id="#+id/label"/>
</RelativeLayout>
I just want to show all apps on home screen with horizontal scroll with bottom dots.
I have also try this method but my issue can't solved

Making buttons in recyclerview and cardview clickable

I've added buttons into a a cardview and recyclerview. I'm struggling to make the buttons clickable. Every time I click the buttons it's actually registering the recyclerview as being clicked.
Activity containing cardview and recyclerview
package com.khumomashapa.notes.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.khumomashapa.notes.R;
import com.khumomashapa.notes.adapter.RecyclerAdapter;
import com.khumomashapa.notes.arraylists.Messages;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class StoreActivity extends AppCompatActivity {
// Widget
RecyclerView recyclerView;
//Firebase
private DatabaseReference mref;
// Variable
private ArrayList<Messages> messagesList;
private RecyclerAdapter recyclerAdapter;
private Context mContext;
Button PurchaseBtn;
Button DownloadBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store);
recyclerView = findViewById(R.id.products_view);
PurchaseBtn = (Button) findViewById(R.id.PurchaseBtn);
DownloadBtn = (Button) findViewById(R.id.DownloadBtn);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
PurchaseBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext()
,recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ImageView imageView = view.findViewById(R.id.ImageView);
Drawable mDrawable = imageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
Intent intent = new Intent(view.getContext(),PreviewActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]bytes = stream.toByteArray();
intent.putExtra("image", bytes);
startActivity(intent);
Messages messages = messagesList.get(position);
Toast.makeText(StoreActivity.this, "You have selected: "+ messages.getTitle(), Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
}
#Override
public void onButtonClicks(View view, int position) {
}
})
);
// Firebase
mref = FirebaseDatabase.getInstance().getReference();
// Arraylist
messagesList = new ArrayList<Messages>();
// Clear arraylist
ClearAll();
// Get data Method
GetDataFromFirebase();
}
private void GetDataFromFirebase(){
Query query = mref.child("Wallpapers");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Messages messages = new Messages();
messages.setImage(snapshot.child("image").getValue().toString());
messages.setTitle(snapshot.child("title").getValue().toString());
messagesList.add(messages);
}
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), messagesList);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ClearAll(){
if(messagesList != null){
messagesList.clear();
if (recyclerAdapter !=null){
recyclerAdapter.notifyDataSetChanged();
}
}
messagesList = new ArrayList<Messages>();
}
}
Recycler Adapter
package com.khumomashapa.notes.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.khumomashapa.notes.R;
import com.khumomashapa.notes.activities.StoreActivity;
import com.khumomashapa.notes.arraylists.Messages;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Messages> messagesList;
Button PurchaseBtn;
Button DownloadBtn;
View imageView;
public RecyclerAdapter(Context mContext, ArrayList<Messages> messagesArrayList) {
this.mContext = mContext;
this.messagesList = messagesArrayList;
View imageView;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.image, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// Textview
holder.textView.setText(messagesList.get(position).getTitle());
holder.PurchaseBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Imageview: Glide library
Glide.with(mContext)
.load(messagesList.get(position).getImage())
.into(holder.imageView);
}
#Override
public int getItemCount() {
return messagesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
// Widgets;
ImageView imageView;
TextView textView;
Button PurchaseBtn;
Button DownloadBtn;
View v;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.ImageView);
textView = itemView.findViewById(R.id.Title);
PurchaseBtn = itemView.findViewById(R.id.PurchaseBtn);
DownloadBtn = itemView.findViewById(R.id.DownloadBtn);
View v;
}
}
}
Recycler Touch Listener
package com.khumomashapa.notes.activities
import android.content.Context
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener
class RecyclerTouchListener(
context: Context?,
recyclerView: RecyclerView,
private val clickListener: ClickListener?
) :
OnItemTouchListener {
private val gestureDetector: GestureDetector
override fun onInterceptTouchEvent(recyclerView: RecyclerView, e: MotionEvent): Boolean {
val child = recyclerView.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, recyclerView.getChildAdapterPosition(child))
}
return false
}
override fun onTouchEvent(recyclerView: RecyclerView, e: MotionEvent) {}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
interface ClickListener {
fun onClick(view: View?, position: Int)
fun onLongClick(view: View?, position: Int)
fun onButtonClicks(view: View?, position: Int)
}
init {
gestureDetector = GestureDetector(context, object : SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent): Boolean {
return true
}
override fun onLongPress(e: MotionEvent) {
val child = recyclerView.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child))
}
}
})
}
}
Cardview layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:contentPadding="5dp"
app:cardCornerRadius="10dp"
app:cardUseCompatPadding="true"
app:cardElevation="3dp"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Imagelayout">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:padding="2dp"
android:id="#+id/ImageView"
android:contentDescription="#string/image" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Imagelayout">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/title"
android:textColor="#color/textColor"
android:textSize="20sp"
android:fontFamily="#font/biorhyme_extralight"
android:id="#+id/Title"/>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/PurchaseBtn"
android:layout_width="350dp"
android:clickable="true"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:onClick="purchase"
android:text="#string/purchase"
android:layout_below="#+id/Title"
android:background="#drawable/btn_rounded"
android:textColor="#color/textColor"
android:textSize="12sp"
app:cornerRadius="20dp"
android:focusable="true" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/DownloadBtn"
android:layout_width="350dp"
android:layout_height="40dp"
android:layout_below="#+id/PurchaseBtn"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_marginTop="6dp"
android:background="#drawable/btn_rounded"
android:text="#string/download"
android:textColor="#color/textColor"
android:textSize="12sp"
android:visibility="invisible"
app:cornerRadius="20dp" />
</RelativeLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
Recyclerview layout
<?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"
tools:context=".activities.StoreActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/products_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout >
Another issue I know I'll encounter is the null reference exception.
How do I reference the buttons from the cardview layout when the content view is set to be shown from the other one.

Recycler View not showing in fragment

I have three fragments: Fragment user, Fragment Home and Fragment Progress.
I'm trying to implement a recylcer view in the homefragment that can recycle images in the recycler view nothing is happening and no error is showing in logcat, i don't know what i'm doing wrong.
1.This is my Custom Adapter:
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.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder>{
#NonNull
private LayoutInflater inflator;
List<Information> data= Collections.emptyList();
public CustomAdapter(Context context, List<Information> data){
inflator= LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=inflator.inflate(R.layout.customlayout, parent,false);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Information current=data.get(position);
holder.icon.setImageResource(current.images);
holder.title.setText(current.title);
}
#Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView icon;
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
icon = (ImageView) itemView.findViewById(R.id.listicon);
title = (TextView) itemView.findViewById(R.id.textView);
}
}
}
This is my Fragment
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.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class HomeFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private CustomAdapter adapter;
int[] IMAGES = {R.drawable.abs,R.drawable.arms,R.drawable.back,R.drawable.chest,R.drawable.full,R.drawable.legs};
private RecyclerView recyclerView;
ArrayList<HashMap<String, String>> data;
private String mParam1;
private String mParam2;
public HomeFragment() {
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView =(RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new CustomAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<Information> getData(){
List<Information> data = new ArrayList<>();
int [] icons = {R.drawable.abs,R.drawable.arms,R.drawable.back,R.drawable.chest,R.drawable.full,R.drawable.legs};
String[] titles={"Abs","Arms","Back","Chest","full","legs"};
for (int i=0; i<icons.length && i<titles.length;i++){
Information current = new Information();
current.images=icons[i];
current.title=titles[i];
data.add(current);
}
return data;
}
}
I can't see to find what I'm doing wrong.
fragmenthome.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".HomeFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true">
</android.support.v7.widget.RecyclerView>
</FrameLayout>
4.Custom_layout.xml
<RelativeLayout
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">
<ImageView
android:id="#+id/listicon"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp"
android:text="TextView" />
you didnt assign the data in your adapter's constructor
this.data = data;
then your item count should be
data.size();
should not be 0.

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>

Error while using ListFragement

I am developing an android app for online payment for which I want to display Lists of restaurants under the tab named Restaurants. Same as this some other tabs will have list below them and a few tabs will have form under them (if possible and not difficult otherwise I will stay with the lists only)
Here is the code I have written. It contains an error in the Adapter class and may be some logical errors which I am not sure about as this is my first ever android app.
Main.java File
package com.example.tabswithswipe;
import com.example.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Retaurants", "Super Store", "Fuel Stations"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
acivity_main.xml File
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
items_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#string/app_name" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name" />
</LinearLayout>
TabPagerAdapter.java Adapter File (Error in this file)
package com.example.tabsswipe.adapter;
import com.example.tabsswipe.*;
import android.app.ListFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new SuperStoreFragment();
case 1:
return new FuelStationsFragment();
case 2:
return new RestaurantsFragment(); //Error Here
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
RestaurantsFragment.java
package com.example.tabsswipe.adapter;
//import com.example.MainActivity.MyAdapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class RestaurantsFragment extends ListFragment {
LayoutInflater inflater;
ViewGroup container;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
this.inflater = inflater;
View rootView = inflater.inflate(R.layout.list_items, container, false);
setListAdapter(new MyAdapter(getActivity(), android.R.layout.simple_list_item_1, R.id.textView1, getResources().getStringArray(R.array.items)));
return rootView;
}
private class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] strings) {
super(context, resource, textViewResourceId, strings);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_items, container, false);
String [] items = getResources().getStringArray(R.array.items);
ImageView iv = (ImageView) row.findViewById(R.id.imageView1);
TextView tv = (TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
if(items[position].equals("kfc"))
{
iv.setImageResource(R.drawable.kfc);
}
else if(items[position].equals("pizzaHut"))
{
iv.setImageResource(R.drawable.pizzahut);
}
else if(items[position].equals("Domino"))
{
iv.setImageResource(R.drawable.dominos);
}
else if(items[position].equals("hardees") )
{
iv.setImageResource(R.drawable.hardees);
}
else if(items[position].equals("TuttiFrutti"))
{
iv.setImageResource(R.drawable.tuttifrutti);
}
else if(items[position].equals("McDonalds"))
{
iv.setImageResource(R.drawable.mcdonalds);
}
else if(items[position].equals("21 Street"))
{
iv.setImageResource(R.drawable.ic_launcher);
}
return row;
}
}
// View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
// return rootView;
// }
}
SuperStoreFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SuperStoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_super_stores, container, false);
return rootView;
}
}
fragment_super_stores.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fa6a6a" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Super Stores Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
FuelStationsFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FuelStationsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fuel_stations, container, false);
return rootView;
}
}
fragment_fuel_stations.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ff8400" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Fuel Stations Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Please tell me how, where and what error occurred. Any kind of help will be really appreciated e.g. Tutorial, code example or even the error resolution of this code. Please ignore my silliness if any. Thank You.

Categories

Resources