Given:method of receiving data which for some reason does not work. adapter for using SwipeCard koloda library
Goal: load photo and name from folder in firebase into shapeableimageview and textview respectively
Problem: the method of receiving data does not work and the name and photo are not loaded from the folder.
Adapter:
public class SwipeAdapter extends BaseAdapter {
private Context context;
private List<Integer> list;
public SwipeAdapter(Context context,List<Integer>list) {
this.context=context;
this.list=list;
}
#Override
public int getCount() {
return 20;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
View view;
if(convertView==null)
{
view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_koloda,parent,false);
}else {
view=convertView;
}
return view;
}
}
Activity with a receive method
private SwipeAdapter adapter;
private List<Integer> list;
private TextView nameusercard;
private ShapeableImageView imageosnovnoe;
Koloda koloda;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
koloda=findViewById(R.id.koloda);
list=new ArrayList<>();
adapter=new SwipeAdapter(this,list);
koloda.setAdapter(adapter);
nameusercard=(TextView) findViewById(R.id.nameusercard);
imageosnovnoe=(ShapeableImageView) findViewById(R.id.imageosnovnoe);
}
private void getUserWInfo()
{
DatabaseReference reference= FirebaseDatabase.getInstance().getReference()
.child("Userw");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()&&snapshot.getChildrenCount()>0)
{
String name=snapshot.child("name").getValue().toString();
nameusercard.setText(name);
if (snapshot.hasChild("image")) {
String image = snapshot.child("image").getValue().toString();
Picasso.get().load(image).into(imageosnovnoe);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Xml item_koloda
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_gravity="center"
android:gravity="center"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_margin="15dp"
app:cardCornerRadius="15dp"
app:cardElevation="5dp">
<LinearLayout
android:id="#+id/linearmain"
android:layout_width="match_parent"
android:layout_height="400dp"
android:orientation="vertical">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/imageosnovnoe"
android:layout_width="match_parent"
android:layout_height="400dp"
android:backgroundTint="#color/white"
android:scaleType="fitXY"
app:srcCompat="#drawable/aaaaa" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearhori"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:layout_gravity="bottom"
android:weightSum="3">
<ImageView
android:id="#+id/like"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:layout_weight="1"
android:src="#drawable/sas"
/>
<ImageView
android:id="#+id/disslike"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:layout_weight="1"
android:src="#drawable/aan"
/>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
I tried to register the method in the adapter but it didn't work either.
Related
I have seen all stack overflow question about this but can't find solution.
Getting error at this line.
String p_score = player_score_US.getText().toString();
My code
public class UpdateScore_activity extends AppCompatActivity {
private RecyclerView recyclerView2;
private DatabaseReference root=FirebaseDatabase.getInstance().getReference("A_matches&Score&contest").child("1").child("Score");
private us_adapter usAdapter;
private TextView playerName;
private Button SaveScorebtn;
public ArrayList<us_model> list1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatescore);
recyclerView2=findViewById(R.id.recycleview2);
SaveScorebtn=(Button)findViewById(R.id.us_saveScore);
EditText player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
playerName=(TextView) findViewById(R.id.Player_Name);
list1=new ArrayList<>();
usAdapter=new us_adapter(this,list1);
recyclerView2.setAdapter(usAdapter);
recyclerView2.setLayoutManager(new LinearLayoutManager(this));
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
String name1 = dataSnapshot.child("Name").getValue(String.class);
us_model myModel=new us_model(name1);
list1.add(myModel);
}
usAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(UpdateScore_activity.this, "hello", Toast.LENGTH_SHORT).show();
}
});
SaveScorebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String p_score = player_score_US.getText().toString();
HashMap<String, String> usermap = new HashMap<>();
usermap.put("Score",p_score);
for (int i=1;i<4;i++){
root.child(String.valueOf(i)).setValue(usermap);
}
openMain();
}
});
}}
Layout file of update Score Activity(Recyclerview)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="500dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Match_Name"
android:gravity="center_horizontal"
android:text="Update Score"
android:textAlignment="center"
android:textColor="#000002"
android:textSize="32dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="456dp"
android:layout_marginTop="10dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleview2"
android:layout_width="match_parent"
android:layout_height="441dp" />
</LinearLayout>
<Button
android:id="#+id/us_saveScore"
android:layout_width="127dp"
android:layout_height="match_parent"
android:layout_marginLeft="62pt"
android:layout_marginTop="5dp"
android:layout_marginRight="57dp"
android:background="#FF80AB"
android:text="Save Score"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Layout file of player card
<?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="115dp"
android:layout_marginTop="10dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="111dp"
app:cardBackgroundColor="#A6D673">
<TextView
android:id="#+id/Player_Name"
android:layout_width="256dp"
android:layout_height="71dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="Player Name"
android:textColor="#000000"
android:textSize="25dp"
android:textStyle="bold" />
<EditText
android:id="#+id/us_Player_Score12"
android:layout_width="79dp"
android:layout_height="61dp"
android:layout_marginLeft="300dp"
android:layout_marginTop="19dp"
android:gravity="center_horizontal"
android:textAlignment="center"
android:textColor="#000000"
android:hint="Enter"
android:textSize="22dp"
android:textStyle="bold" />
</androidx.cardview.widget.CardView>
</LinearLayout>
Adapter class
public class us_adapter extends RecyclerView.Adapter<us_adapter.Myviewholder> {
ArrayList<us_model> mlist1;
Context context;
public us_adapter(Context context, ArrayList<us_model> mlist1){
this.context=context;
this.mlist1=mlist1;
}
public us_adapter.Myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v=LayoutInflater.from(context).inflate(R.layout.updatescore_row,parent,false);
return new Myviewholder(v);
}
#Override
public void onBindViewHolder(#NonNull Myviewholder holder, int position) {
us_model model1 =mlist1.get(position);
holder.Name.setText(model1.getName());
}
public int getItemCount() {
return mlist1.size();
}
public class Myviewholder extends RecyclerView.ViewHolder {
TextView Name;
Button update;
public Myviewholder(#NonNull View itemView) {
super(itemView);
Name=itemView.findViewById(R.id.Player_Name);
}
}
}
Model class
public class us_model{
private String Name;
public us_model(String Name) {
this.Name = Name;
}
public String getName() {
return Name;
}
}
There are two solutions that you could try for this problem.
Solution 1:
From
EditText player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
To
final EditText player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
The reason is, if two methods see the same local variable in Java, Java wants you to ensure you will not change it, In that case you have to make it final.
Solution 2:
As well as, you could make it a global variable.
public class UpdateScore_activity extends AppCompatActivity {
private RecyclerView recyclerView2;
private DatabaseReference root=FirebaseDatabase.getInstance().getReference("A_matches&Score&contest").child("1").child("Score");
private us_adapter usAdapter;
private TextView playerName;
private Button SaveScorebtn;
private EditText player_score_US;
public ArrayList<us_model> list1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatescore);
recyclerView2=findViewById(R.id.recycleview2);
SaveScorebtn=(Button)findViewById(R.id.us_saveScore);
player_score_US=(EditText) findViewById(R.id.us_Player_Score12);
playerName=(TextView) findViewById(R.id.Player_Name);
list1=new ArrayList<>();
usAdapter=new us_adapter(this,list1);
recyclerView2.setAdapter(usAdapter);
recyclerView2.setLayoutManager(new LinearLayoutManager(this));
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
String name1 = dataSnapshot.child("Name").getValue(String.class);
us_model myModel=new us_model(name1);
list1.add(myModel);
}
usAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(UpdateScore_activity.this, "hello", Toast.LENGTH_SHORT).show();
}
});
SaveScorebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String p_score = player_score_US.getText().toString();
HashMap<String, String> usermap = new HashMap<>();
usermap.put("Score",p_score);
for (int i=1;i<4;i++){
root.child(String.valueOf(i)).setValue(usermap);
}
openMain();
}
});
}}
Please, help to figure out why my implementation of RecyclerView doesn't show anything.
Retrieving data asynchronously and result is successfull, but don't know how to display it correctly.
Activity
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
checkAndRequestPermissions(Manifest.permission.INTERNET);
RecyclerView recyclerView = binding.recyclerView;
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
NewsAdapter adapter = new NewsAdapter();
recyclerView.setAdapter(adapter);
RssService.runRssFeed(newsList -> {
System.out.println("SIZE ----- " + newsList.size());
adapter.setItems(newsList);
});
}
}
Adapter
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private final List<NewsModel> news = new ArrayList<>();
#Override
public NewsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_item, parent, false);
return new ViewHolder(view);
}
public void setItems(List<NewsModel> news) {
this.news.addAll(news);
notifyDataSetChanged();
}
public void clearItems() {
this.news.clear();
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(#NonNull NewsAdapter.ViewHolder holder, int position) {
holder.title.setText(news.get(holder.getAdapterPosition()).getTitle());
holder.date.setText(news.get(holder.getAdapterPosition()).getDate());
holder.link.setText(news.get(holder.getAdapterPosition()).getLink());
}
#Override
public int getItemCount() {
return news.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
final TextView title, date, link;
public ViewHolder(View view) {
super(view);
title = view.findViewById(R.id.titleTxt);
date = view.findViewById(R.id.dateTxt);
link = view.findViewById(R.id.linkTxt);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
</LinearLayout>
news_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:orientation="vertical">
<TextView
android:id="#+id/titleTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:textSize="16sp"
android:textStyle="normal"
android:typeface="sans" />
<TextView
android:id="#+id/linkTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="normal"
android:typeface="sans" />
<TextView
android:id="#+id/dateTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginTop="10dp"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="normal"
android:typeface="sans" />
</LinearLayout>
I think It showed correctly but you can't see because your text color is white
**issue in these lines**
holder.title.setText(news.get(holder.getAdapterPosition()).getTitle());
holder.date.setText(news.get(holder.getAdapterPosition()).getDate());
holder.link.setText(news.get(holder.getAdapterPosition()).getLink());
change these like
holder.title.setText(news.get(position).getTitle());
I have created a wallpaper app where I'm loading images from the firebase database in recyclerview. When I click on recyclerview item(image) that item's image URL is sent to the next activity and then that URL is loaded into imageView using glide.
I want to change this to something like Image-Slider. By clicking on the recyclerView item I want to show that image in full screen and slide from left or right(next or previous). But I don't know how to do that.
Here is my code.
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
adapter = new FeaturedAdapter(list);
recyclerView.setAdapter(adapter);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Wallpaper All");
Query query = databaseReference.orderByChild("dark").equalTo(true);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
FeaturedModel model = dataSnapshot1.getValue(FeaturedModel.class);
list.add(model);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("TAG_DATABASE_ERROR", databaseError.getMessage());
}
});
FeaturedAdapter.java
public class FeaturedAdapter extends RecyclerView.Adapter<FeaturedAdapter.ViewHolder> {
private List<FeaturedModel> featuredModels;
public FeaturedAdapter(List<FeaturedModel> featuredModels) {
this.featuredModels = featuredModels;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_image, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setData(featuredModels.get(position).getImageLink()
, position,
featuredModels.get(position).isPremium());
}
#Override
public int getItemCount() {
return featuredModels.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private ImageView premiumImage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageview);
premiumImage = itemView.findViewById(R.id.premium);
}
private void setData(final String url, final int position, boolean premium) {
Glide.with(itemView.getContext().getApplicationContext()).load(url).into(imageView);
if (premium) {
premiumImage.setVisibility(View.VISIBLE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), PremiumViewActivity.class);
//setIntent.putExtra("title", url);
setIntent.putExtra("images", featuredModels.get(getAdapterPosition()).getImageLink());
setIntent.putExtra("id", featuredModels.get(position).getId());
itemView.getContext().startActivity(setIntent);
}
});
} else {
premiumImage.setVisibility(View.GONE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), ViewActivity.class);
//setIntent.putExtra("title", url);
setIntent.putExtra("images", featuredModels.get(getAdapterPosition()).getImageLink());
setIntent.putExtra("id", featuredModels.get(position).getId());
itemView.getContext().startActivity(setIntent);
}
});
}
}
}
}
ViewActivity
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
relativeLayout.setBackgroundColor(color);
Glide.with(this)
.load(getIntent().getStringExtra("images"))
.timeout(6000)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
})
.into(imageView);
setBackgroundWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBackgroundImage();
}
});
}
private void setBackgroundImage() {
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
try {
manager.setBitmap(bitmap);
Toasty.success(getApplicationContext(), "Set Wallpaper Successfully", Toast.LENGTH_SHORT, true).show();
} catch (IOException e) {
Toasty.warning(this, "Wallpaper not load yet!", Toast.LENGTH_SHORT, true).show();
}
}
activity_view.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.PremiumViewActivity">
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#null"
android:scaleType="centerCrop"
android:src="#00BCD4"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/lottieSuccess"
android:layout_width="180dp"
android:layout_height="180dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:lottie_fileName="checked.json" />
<RelativeLayout
android:id="#+id/wallpaper_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent">
<ImageButton
android:id="#+id/saveImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:contentDescription="#null"
android:src="#drawable/save" />
<Button
android:id="#+id/setWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="4dp"
android:layout_marginEnd="8dp"
android:background="#drawable/set_as_wallpaper_btn"
android:minWidth="230dp"
android:text="Set as wallpaper"
android:textColor="#000"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:orientation="horizontal">
<CheckBox
android:id="#+id/favoritesBtn_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:button="#drawable/favourite_checkbox_selector" />
<ImageButton
android:id="#+id/shareBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:background="#drawable/share"
android:contentDescription="#null" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/ads_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="12dp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent">
<Button
android:id="#+id/watch_ads"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:drawableStart="#drawable/advertizing"
android:paddingStart="50dp"
android:paddingEnd="50dp"
android:stateListAnimator="#null"
android:text="Watch Video Ad"
android:textColor="#000"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/watch_ads">
<Button
android:id="#+id/unlock_withCoins"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginStart="20dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:drawableStart="#drawable/diamond"
android:paddingStart="50dp"
android:paddingEnd="50dp"
android:stateListAnimator="#null"
android:text="Unlock with diamonds"
android:textColor="#000"
android:textStyle="bold" />
<TextView
android:id="#+id/diamonds_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:text="Total Diamonds: 0"
android:textSize="10sp"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
custom_image.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:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:background="#fff"
app:cardCornerRadius="10dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#null"
android:scaleType="centerCrop"
android:src="#color/colorPrimary" />
<ImageView
android:id="#+id/premium"
android:contentDescription="#null"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_margin="10dp"
app:srcCompat="#drawable/diamond" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
Structure
MainActivity
|
| //Click button to open
|
FragActivity
|
| //FrameLayout
|
Fragment
|
| //here is the recyclerView
| //Open new Activity to view image
ViewActivity
Screen Recording
This can be solved by using ViewPager or ViewPager2 in Android
First create an Adapter
ImageSwiperAdapter2.java
public class ImageSwiperAdapter2 extends RecyclerView.Adapter<ImageSwiperAdapter2.ImageSwiper> {
private List<FeaturedModel> list;
private Context context;
public ImageSwiperAdapter2(List<FeaturedModel> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public ImageSwiper onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.slidingimages,
parent, false);
return new ImageSwiper(view);
}
#Override
public void onBindViewHolder(#NonNull final ImageSwiper holder, int position) {
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
holder.relativeLayout.setBackgroundColor(color);
Glide.with(context.getApplicationContext())
.load(list.get(position).getImageLink())
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
holder.relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
holder.relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
})
.into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
class ImageSwiper extends RecyclerView.ViewHolder {
private ImageView imageView;
public ImageSwiper(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
In ViewActivity/SwiperActivity.java
public class SwiperActivity extends AppCompatActivity {
private ViewPager2 viewPager;
private List<FeaturedModel> list;
private ImageSwiperAdapter2 adapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swiper);
viewPager = findViewById(R.id.view_pager);
final int pos = getIntent().getIntExtra("pos", 0);
Singleton singleton = Singleton.getInstance();
list = new ArrayList<>();
list = singleton.getListSin();
adapter2 = new ImageSwiperAdapter2(list, this);
viewPager.setAdapter(adapter2);
viewPager.setCurrentItem(pos);
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Toast.makeText(SwiperActivity.this, "Selected: " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
}
You can pass the list and clicked item position in FeaturedAdapter.
In your FeaturedAdapter's setData method
private void setData(final String url, final int position, boolean premium) {
Glide.with(itemView.getContext().getApplicationContext()).load(url).into(imageView);
final Singleton a = Singleton.getInstance();
a.setListSin(featuredModels);
if (premium) {
premiumImage.setVisibility(View.VISIBLE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), SwiperActivity.class);
setIntent.putExtra("pos", position);
itemView.getContext().startActivity(setIntent);
CustomIntent.customType(itemView.getContext(), "fadein-to-fadeout");
}
});
} else {
premiumImage.setVisibility(View.GONE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), SwiperActivity.class);
setIntent.putExtra("pos", position);
itemView.getContext().startActivity(setIntent);
CustomIntent.customType(itemView.getContext(), "fadein-to-fadeout");
}
});
}
}
slidingimages.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">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#null"
android:scaleType="centerCrop" />
</RelativeLayout>
activity_swiper.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=".SwiperActivity">
<androidx.viewpager2.widget.ViewPager2
android:orientation="horizontal"
android:id="#+id/view_pager"
android:layoutDirection="inherit"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Since the ViewActivity must show all the images(when slided) it must contain the adapter with the set of image urls.
Instead of using an ImageView, use a RecyclerView in the ViewActivity and attach the adapter. In your code, do the following to make the recycler view horizontal and add slide functionality.
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
Few Days ago, I had been looking for similar requirement for showing slid-able image View.
This situation can be solved using ViewPager in Android.
You can use following Tutorials for building such Slide Image View using ViewPager
Java Resources
Blog Tutorial
Video Tutorial
Kotlin Resources
Video Tutorial
I tried to retrive images from firebase with correct url link. The RecyclerView keep shown "first" info of Food which is cookie-milk-cup:
This is my firebase data structure:
all_uploaded_image //directory
|-cookie milk cup
|-description: "yes!" //shown successful
|-image_uri: "content://com.android.providers.media.documents..." //no necessary in this case
|-name: "cookie milk cup" //shown successful
|-price: "1.20" //not shown
|-uploader_uid: "GSsY4tEo5ZZpS8kkJEpWGLCbFmC3" //no necessary in this case
fish n chips //recursive only on cookie milk cup, so nothing appear in here
|-description: "delicious fc"
|-image_uri: "content://com.android.providers.media.documents..."
|-name: "fish n chips"
|-price: "1.20"
|-uploader_uid: "GSsY4tEo5ZZpS8kkJEpWGLCbFmC3"
I am using android with java, want to get the info from firebase using fragment.
This is the AllFOodFragment.java
public class AllFoodFragment extends Fragment {
private View contactsView;
private ArrayList<Food> entries;
private DatabaseReference ref;
private FirebaseDatabase dbr;
private FoodAdapter adapter;
private RecyclerView recycler_view;
public AllFoodFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View contactsView = inflater.inflate(R.layout.home_main, container, false); //v
recycler_view = (RecyclerView) contactsView.findViewById(R.id.recycler_view);
recycler_view.setHasFixedSize(true);
recycler_view.setItemAnimator(new DefaultItemAnimator());
final FragmentActivity ga = getActivity(); //2a
LinearLayoutManager lm = new LinearLayoutManager(ga); //2
recycler_view.setLayoutManager(lm);
entries = new ArrayList<Food>();
ref = FirebaseDatabase.getInstance().getReference().child("all_uploaded_image");
ref.addChildEventListener(new ChildEventListener(){
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for(DataSnapshot ds: dataSnapshot.getChildren()) {
//Log.e("Count " ,"" + dataSnapshot.getChildrenCount());
Food data = dataSnapshot.getValue(Food.class);
//data.setPrice(dataSnapshot.child("price").getValue().toString());
//data.setImageUrl(dataSnapshot.child("image_uri").getValue().toString());
entries.add(data);
//Log.e("Get All Description", data.get_price());
}
adapter = new FoodAdapter(getActivity(), entries);
adapter.notifyDataSetChanged();
adapter.setListFood(entries);
//3; No adapter attached in here, but program runs
recycler_view.setAdapter(adapter);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
return contactsView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void onViewCreated(View view, #Nullable Bundle savedUbstabceState){
super.onViewCreated(view, savedUbstabceState);
this.contactsView = view;
}
}
And, this is FoodAdapter.java
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder> {
private Context m_context;
private ArrayList<Food> m_listFood = new ArrayList<Food>();
public FoodAdapter(Context context, ArrayList<Food> food_list) {//m_context, food_list
this.m_context = context;
this.m_listFood = food_list;
}
#NonNull
#Override
public FoodViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_fragment_all_food, parent, false);
return new FoodViewHolder(v);
}
public class FoodViewHolder extends RecyclerView.ViewHolder{
public ImageView FoodIcon;
public TextView FoodName;
public TextView FoodDescription;
public TextView FoodPrice;
public Button Fooddetail;
public FoodViewHolder (View itemView){
super(itemView);
FoodIcon = (ImageView)itemView.findViewById(R.id.thumbnail); //icon
FoodName = itemView.findViewById(R.id.foodname);
FoodDescription = itemView.findViewById(R.id.fooddescription);
FoodPrice = itemView.findViewById(R.id.foodprice);
Fooddetail = itemView.findViewById(R.id.fooddetail);
}
public void onClick(View view) {
}
}
#Override
public void onBindViewHolder(#NonNull FoodViewHolder holder, int position) {
Food f = m_listFood.get(position);
holder.FoodName.setText(f.get_name());
holder.FoodDescription.setText(f.get_description());
holder.FoodPrice.setText(f.get_price());
holder.FoodPrice.setText(f.get_url());
//Picasso.get().load(m_listFood.get(position).get_url()).fit().into(holder.FoodIcon);
Glide.with(m_context).load(f.get_url()).into(holder.FoodIcon); //getListFood().get(position).get_icon()
}
#Override
public int getItemCount() {
return m_listFood.size();
}
public Context get_context() {
return m_context;
}
public void setListFood(ArrayList<Food> m_listFood){
this.m_listFood = m_listFood;
}
}
this is item_fragment_all_food.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="4dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView //icon not shown, white
android:id="#+id/thumbnail"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/star_big_on" />
<TextView
android:id="#+id/foodname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="191dp"
android:layout_marginTop="16dp"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/fooddescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/foodname"
android:layout_marginEnd="86dp"
android:layout_marginBottom="-91dp"
android:text="Description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/foodname" />
<TextView
android:id="#+id/foodprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="85dp"
android:layout_marginEnd="95dp"
android:text="Price"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.487"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/fooddescription"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/fooddetail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginEnd="79dp"
android:layout_marginBottom="16dp"
android:background="#color/colorPrimary"
android:text="Detail"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/foodprice"
app:layout_constraintVertical_bias="0.0" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
And, this is activity_main.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=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.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" />
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:autofillHints="email"
android:layout_margin="15dp"
android:inputType="textEmailAddress"
android:hint="Enter Email"
android:id="#+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_margin="15dp"
android:inputType="textPassword"
android:hint="Enter Password"
android:id="#+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:layout_margin="15dp"
android:hint="Register"
android:id="#+id/btn_register"
android:layout_width="match_parent"
android:onClick="click_to_register_new_user"
android:layout_height="wrap_content" />
<Button
android:layout_margin="15dp"
android:hint="Login"
android:id="#+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="137dp"
android:text="#string/reset_string" />
</RelativeLayout>
Lastly, my Food Model
public class Food {
public String name;
public String description;
public String price;
public String img_url;
public String icon;
public Food() {
//empty
}
public Food(String name, String description, String price, String imageUrl) {
if (name.trim().equals("")) {
name = "No Name";
}
this.name = name;
this.description = description;
this.price = price;
this.img_url = imageUrl;
}
public String get_name() {
return name;
}
public String get_description() {
return description;
}
public String get_price() {
return price;
}
public String get_icon() {
return icon;
}
public String get_url() {
return img_url;
}
public void setPrice(String price) {
this.price = price;
}
public void setImageUrl(String imageUrl) {
img_url = imageUrl;
}
public void set_icon(String icon) {
this.icon = icon;
}
}
The error I get is E/RecyclerView: No adapter attached; skipping layout
and No setter/field for image_uri found on class com.example.hungrystomach.Model.Food [but really I do not want image_uri shown in my recyclerview so I skip the TextView]
The recyclerView does not have any Image shown even I've FoodIcon with thumbnail in FOodAdaper.java. I've tried for three weeks already still no hope. I suppose to get all the info I need. I know it is little bit long but any suggestion and answer would appreciate.
I want to make this:
I have a RecyclerView, wherein for each item I create I want to show the time when the item was created. I want to display the time within this item.
My code:
public class VerIncidencia extends AppCompatActivity {
private FirebaseRecyclerAdapter mAdapter;
private DatabaseReference mDatabase;
String idIncidencia;
String idEmpresa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ver_incidencia);
String uid = FirebaseAuth.getInstance().getUid();
idIncidencia = getIntent().getStringExtra("INCIDENCIA_KEY");
idEmpresa = getIntent().getStringExtra("EMPRESA_KEY");
mDatabase = FirebaseDatabase.getInstance().getReference().child("incidencia").child(uid);
RecyclerView recyclerView = findViewById(R.id.list_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Query postsQuery = mDatabase;
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Incidencia>()
.setQuery(postsQuery, Incidencia.class)
.setLifecycleOwner(this)
.build();
mAdapter = new FirebaseRecyclerAdapter<Incidencia, IncidenciaViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull IncidenciaViewHolder holder, final int position, #NonNull final Incidencia empresa) {
holder.departamento.setText(empresa.departamento);
holder.prioridad.setText(empresa.prioridad);
holder.motivo.setText(empresa.motivo);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(VerIncidencia.this, VerIncidenciaCompleta.class);
intent.putExtra("INCIDENCIA_KEY", getRef(position).getKey());
startActivity(intent);
}
});
}
#Override
public IncidenciaViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_incidencia, parent, false);
return new IncidenciaViewHolder(view);
}
};
recyclerView.setAdapter(mAdapter);
}
}
ViewHolder:
public class IncidenciaViewHolder extends RecyclerView.ViewHolder{
TextView departamento;
TextView prioridad;
TextView motivo;
public IncidenciaViewHolder(View itemView) {
super(itemView);
departamento = itemView.findViewById(R.id.departamento);
prioridad = itemView.findViewById(R.id.prioridad);
motivo = itemView.findViewById(R.id.motivo);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.CardView
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="wrap_content"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/departamento"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="-40dp"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/prioridad"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="30dp"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/motivo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_marginTop="85dp"
android:textColor="#android:color/black"
android:textSize="25sp" />
</LinearLayout>