I am building a social media app, and I wanted to add story scroll view. The problem I am facing is my recycler view is showing only two items however I gave it 4 or more.
I am using horizontal scroll view because I have a first item that says "click to add story" which is different than those items in recycler view. I am new in android building so any help would be appreciated, and I checked different solutions but none were helpful. The only success I got was to increase layout-width of recycler view to 1000dp that helps in scrolling but that's not efficient. My home fragment code, where problem is occurred:
<HorizontalScrollView
android:id="#+id/horizontal_story_scroll_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:isScrollContainer="true"
android:paddingLeft="5dp"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbars="none"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="120dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="160dp"
android:layout_height="match_parent"
android:paddingRight="5dp">
<com.makeramen.roundedimageview.RoundedImageView
android:id="#+id/click_add_story_img_id"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
android:src="#drawable/rain_drops_bg"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:riv_border_color="#333333"
app:riv_border_width="2dip"
app:riv_corner_radius="20dip"
app:riv_mutate_background="true"
app:riv_tile_mode="repeat" />
<com.makeramen.roundedimageview.RoundedImageView
android:id="#+id/user_story_img_id"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#color/black_shade"
app:background="#color/light_red"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/click_add_story_img_id"
app:layout_constraintStart_toStartOf="#+id/click_add_story_img_id"
app:layout_constraintTop_toTopOf="parent"
app:riv_border_color="#333333"
app:riv_border_width="2dip"
app:riv_corner_radius="20dip"
app:riv_mutate_background="true"
app:riv_tile_mode="repeat" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/add_story"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="16dp"
android:padding="5dp"
android:src="#drawable/add_3_icon"
app:layout_constraintBottom_toTopOf="#+id/textView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/click_add_story_img_id" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:fontFamily="#font/baloo_bhai"
android:text="Click to add Story"
android:textColor="#color/white"
app:layout_constraintBottom_toTopOf="#+id/click_add_story_img_id"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/add_story" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/story_rv_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</HorizontalScrollView>
My Adapter:
package com.assadcoorp.socialstar.Package;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.assadcoorp.socialstar.DataTypes.StoryDataType;
import com.assadcoorp.socialstar.R;
import java.util.ArrayList;
public class StoryAdapter extends RecyclerView.Adapter<StoryAdapter.viewHolder>{
ArrayList<StoryDataType> list;
Context context;
public StoryAdapter(ArrayList<StoryDataType> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.sample_story,parent,false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
StoryDataType model=list.get(position);
holder.story_image.setImageResource(model.getStory());
holder.profile_pic.setImageResource(model.getProfile());
holder.name.setText(model.getName());
holder.live_status.setImageResource(model.getStatus());
}
#Override
public int getItemCount() {
return list.size();
}
public class viewHolder extends RecyclerView.ViewHolder{
ImageView story_image,profile_pic,live_status;
TextView name;
public viewHolder(#NonNull View itemView) {
super(itemView);
story_image=itemView.findViewById(R.id.user_story_img_id);
profile_pic=itemView.findViewById(R.id.user_profile_pic_img_id);
live_status=itemView.findViewById(R.id.live_status_id);
name=itemView.findViewById(R.id.user_name_txt_id);
}
}
}
My database:
package com.assadcoorp.socialstar.DataTypes;
public class StoryDataType {
int status;
String name;
int story,profile;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStory() {
return story;
}
public void setStory(int story) {
this.story = story;
}
public int getProfile() {
return profile;
}
public void setProfile(int profile) {
this.profile = profile;
}
public StoryDataType(int status, String name, int story, int profile) {
this.status = status;
this.name = name;
this.story = story;
this.profile = profile;
}
}
and home fragment:
package com.assadcoorp.socialstar;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.Toast;
import com.assadcoorp.socialstar.DataTypes.StoryDataType;
import com.assadcoorp.socialstar.Package.StoryAdapter;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
RecyclerView story_rv;
ArrayList<StoryDataType> story_list;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_home, container, false);
story_rv=view.findViewById(R.id.story_rv_id);
story_list = new ArrayList<>();
story_list.add(new StoryDataType(R.drawable.live,"Dragon",R.drawable.rain_drops_bg,R.drawable.profile_icon));
story_list.add(new StoryDataType(R.drawable.live,"Dragon",R.drawable.rain_drops_bg,R.drawable.profile_icon));
story_list.add(new StoryDataType(R.drawable.live,"Dragon",R.drawable.rain_drops_bg,R.drawable.profile_icon));
story_list.add(new StoryDataType(R.drawable.live,"Dragon",R.drawable.rain_drops_bg,R.drawable.profile_icon));
StoryAdapter adapter=new StoryAdapter(story_list,getContext());
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
story_rv.setLayoutManager(linearLayoutManager);
//story_rv.setNestedScrollingEnabled(true);
story_rv.setAdapter(adapter);
return view;
}
}
and sample recycler view:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp">
<com.makeramen.roundedimageview.RoundedImageView
android:id="#+id/user_story_img_id"
android:layout_width="160dp"
android:layout_height="120dp"
android:scaleType="centerCrop"
android:src="#drawable/rain_drops_bg"
app:background="#color/light_red"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:riv_border_color="#333333"
app:riv_corner_radius="20dip"
app:riv_mutate_background="true"
app:riv_tile_mode="repeat" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/user_profile_pic_img_id"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginEnd="6dp"
android:layout_marginBottom="70dp"
android:padding="5dp"
android:src="#drawable/profile_icon"
app:layout_constraintBottom_toBottomOf="#+id/user_story_img_id"
app:layout_constraintEnd_toEndOf="#+id/user_story_img_id"
app:layout_constraintTop_toTopOf="#+id/user_story_img_id" />
<View
android:id="#+id/user_profile_pic_ring_id"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#drawable/circle_4"
app:layout_constraintBottom_toBottomOf="#+id/user_profile_pic_img_id"
app:layout_constraintEnd_toEndOf="#+id/user_profile_pic_img_id"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="#+id/user_profile_pic_img_id"
app:layout_constraintTop_toTopOf="#+id/user_profile_pic_img_id"
app:layout_constraintVertical_bias="1.0" />
<ImageView
android:id="#+id/live_status_id"
android:layout_width="50dp"
android:layout_height="40dp"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
app:layout_constraintStart_toStartOf="#+id/user_story_img_id"
app:layout_constraintTop_toTopOf="#+id/user_story_img_id"
app:srcCompat="#drawable/live" />
<TextView
android:id="#+id/user_name_txt_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginBottom="8dp"
android:background="#color/light_black_shade"
android:text="TextView"
android:textColor="#FFFFFF"
android:textSize="18dp"
app:layout_constraintBottom_toBottomOf="#+id/user_story_img_id"
app:layout_constraintStart_toStartOf="#+id/user_story_img_id" />
</androidx.constraintlayout.widget.ConstraintLayout>
try to initialize your Arraylist in the HomeFragment class like this ArrayList story_list=new ArrayList();
and if you are using firebase to get the data create a empty constructor in the StoryDataType class;
Related
I'm using a recyclerview to show restaurants that are previously saved in a database, and I'm using volley to get their information, but it is not working, I suspect that is a problem with volley code, can you guys help me at this point? I will be very happy!
I've discovered that if I start another activity then I go back to home, it returns the recyclerview again, but if I change the fragment it disapears.
Here is how the app is working for now: Result
Fragment Home code:
package com.example.techtable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Home extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private ArrayList<restaurantes> restaurantesArrayList;
private static final String url = "https://cybersquare.dev.br/php/obterRestaurantes.php";
TextView txterro;
private RecyclerView recyclerview;
public Home() {
// Required empty public constructor
}
public static Pedidos newInstance(String param1, String param2) {
Pedidos fragment = new Pedidos();
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);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedIntanceState){
super.onViewCreated(view, savedIntanceState);
dataInitialize();
recyclerview = view.findViewById(R.id.recyclerView);
recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerview.setHasFixedSize(true);
adapterRestaurante myAdapter = new adapterRestaurante(getContext(),restaurantesArrayList);
recyclerview.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
private void dataInitialize() {
restaurantesArrayList = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
response -> {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
String titulo = object.getString("nome");
String descricao = object.getString("descricao");
int avaliacao = object.getInt("avaliacao");
int valor = object.getInt("valor");
String fotoResto = object.getString("fotoRestaurante");
restaurantesArrayList.add(new restaurantes(titulo, descricao, avaliacao, valor, fotoResto));
}
}catch (Exception e){
}
}, error -> Toast.makeText(getActivity(), error.toString(),Toast.LENGTH_LONG).show());
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
}
Recyclerview adapter:
package com.example.techtable;
import android.content.Context;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class adapterRestaurante extends RecyclerView.Adapter<adapterRestaurante.MyViewHolder>{
Context context;
ArrayList<restaurantes> restaurantesArrayList;
public adapterRestaurante(Context context, ArrayList<restaurantes> restaurantesArrayList) {
this.context = context;
this.restaurantesArrayList = restaurantesArrayList;
}
#NonNull
#Override
public adapterRestaurante.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.layout_linha_pesquisa, parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull adapterRestaurante.MyViewHolder holder, int position) {
restaurantes restaurantes = restaurantesArrayList.get(position);
holder.titResto.setText(restaurantes.titResto);
holder.descResto.setText(restaurantes.descResto);
Picasso.get().load("fotoPerfil").into(holder.fotoResto);
}
#Override
public int getItemCount() {
return restaurantesArrayList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
ImageView fotoResto;
ImageView primeiraEstrela;
ImageView segundaEstrela;
ImageView terceiraEstrela;
ImageView primeiroDolar;
ImageView segundoDolar;
ImageView terceiroDolar;
TextView titResto;
TextView descResto;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
titResto = itemView.findViewById(R.id.titResto01);
descResto = itemView.findViewById(R.id.descResto01);
fotoResto = itemView.findViewById(R.id.fotoResto01);
primeiraEstrela = itemView.findViewById(R.id.estrela11);
segundaEstrela = itemView.findViewById(R.id.estrela12);
terceiraEstrela = itemView.findViewById(R.id.estrela13);
primeiroDolar = itemView.findViewById(R.id.valor11);
segundoDolar = itemView.findViewById(R.id.valor12);
terceiroDolar = itemView.findViewById(R.id.valor13);
}
}
}
Arraylist restaurantes
package com.example.techtable;
import android.net.Uri;
import android.widget.ImageView;
public class restaurantes {
String titResto;
String descResto;
int avaliacaoResto;
int valorResto;
String fotoResto;
public restaurantes(String titResto, String descResto, int avaliacaoResto, int valorResto, String fotoResto) {
this.titResto = titResto;
this.valorResto = valorResto;
this.avaliacaoResto = avaliacaoResto;
this.fotoResto = fotoResto;
this.descResto = descResto;
}
}
MyViewHolder layout
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/ConstainerResto01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="15dp"
android:background="#drawable/botaoresto"
android:onClick="teste"
android:paddingTop="20dp"
android:paddingBottom="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/fotoResto01"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginStart="20dp"
android:scaleType="centerInside"
android:src="#drawable/botaoredondo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginStart="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/fotoResto01"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout7"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_marginEnd="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/estrela11"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/ic_posticestrelacheia"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/estrela12"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="25dp"
android:src="#drawable/ic_posticestrelameia"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/estrela13"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="50dp"
android:src="#drawable/ic_posticestrelavazia"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/valor11"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/ic_posticdolarcheio"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/valor12"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="25dp"
android:src="#drawable/ic_posticdolarcheio"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/valor13"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="50dp"
android:src="#drawable/ic_posticdolarmeia"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginEnd="25dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/constraintLayout7"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/descResto01"
android:layout_width="118dp"
android:layout_height="49dp"
android:fontFamily="#font/roboto_thin"
android:text="Lorem Ipsum Dolor Sit Amet Lorem Ipsum Dolor Sit Amet"
android:textColor="#color/cinza_medio"
android:textSize="15sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/titResto01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto_black"
android:text="Restaurante 01"
android:textColor="#color/laranja"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Fragment Home layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FFFFFF"
tools:context=".Home">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="25dp"
android:layout_marginTop="70dp"
android:layout_marginEnd="25dp"
android:layout_marginBottom="1dp"
app:layout_constraintBottom_toTopOf="#+id/recyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/txtUsuario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:fontFamily="#font/roboto_medium"
android:text="Olá usuário!"
android:textColor="#color/black"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/textView29"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView20" />
<ImageView
android:id="#+id/imageView20"
android:layout_width="200dp"
android:layout_height="80dp"
android:src="#drawable/logotechtablecolorida"
app:layout_constraintBottom_toTopOf="#+id/txtUsuario"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView29"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:fontFamily="#font/roboto_light"
android:text="Escolha seu restaurante e faça seu pedido"
android:textAlignment="viewStart"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtUsuario" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="80dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/constraintLayout8" />
</androidx.constraintlayout.widget.ConstraintLayout>
JSON file:
<?php
header('content-type: application/json');
$con = mysqli_connect("localhost","cyber536_admin","mJEn#*a]0Jc*","cyber536_techtable");
mysqli_set_charset($con,'utf-8');
$query = "select nome, avaliacao, descricao, fotoRestaurante, valor from restaurantes;";
$res = mysqli_query($con,$query);
$json_data = array();
while($row = mysqli_fetch_assoc($res)){
$json_data[] = $row;
}
echo json_encode($json_data);
?>
My problem 1:I'm using android studio to build a recycler view.However,when I run the code,this notification pop up.
My problem 2:In MainActivity.java ,an error that shown cannot find system variable Recyclerview in line 23 pop up.May I know how to solve it?becuz I declared it already.
Below are my codes:
(MainActivity.java:)
package com.example.recyclerviewdemo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
List <Details> detailsList;
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.recyclerView);
detailsList=new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
//passing data to model class
for (int i=0;i<=10;i++){
Details details=new Details("Java "+i,"This is description " +i);
detailsList.add(details);
}
myAdapter=new MyAdapter(detailsList);
recyclerView.setAdapter(myAdapter);
}
}
(activity_main.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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="409dp"
android:layout_height="729dp"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
MyAdapter.java:
package com.example.recyclerviewdemo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.widget.TextViewOnReceiveContentListener;
import androidx.recyclerview.widget.RecyclerView;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Details> detailsList;
public MyAdapter(List<Details> detailsList) {
this.detailsList = detailsList;
}
#NonNull
#NotNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(
R.layout.rv_item_list,
parent,
false
);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull #NotNull MyAdapter.MyViewHolder holder, int
position) {
holder.tvTitle.setText(detailsList.get(position).getTitle());
holder.tvDesc.setText(detailsList.get(position).getTitle());
}
#Override
public int getItemCount() {
return detailsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvDesc;
public MyViewHolder(#NonNull #org.jetbrains.annotations.NotNull View itemView) {
super(itemView);
tvTitle=itemView.findViewById(R.id.tvTitle);
tvDesc=itemView.findViewById(R.id.tvDescription);
}
}
}
Details.java:
package com.example.recyclerviewdemo;
public class Details {
private String title;
private String description;
public Details(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
}
rv_item_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
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="5dp"
app:cardElevation="5dp"
android:layout_margin="5dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/a" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="24dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginEnd="200dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toBottomOf="#+id/tvTitle" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
You forget to declare the id in the XML file..Add this in your activity 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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="409dp"
android:layout_height="729dp"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
So here is my problem, I got an API that gives me the lastest news of many sources. Each one of them goes with a cardview. The problem here is, while I'm using the swipeRefresh, it gets duplicated cardViews with the same news, like if I have 10 news, it duplicates to 20 with the same ones.
Here is my code where I apply the swipeRefresh:
package com.example.newsapp4;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.example.newsapp4.Model.Articles;
import com.example.newsapp4.Model.Headlines;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class bbcnews extends AppCompatActivity {
Adapter adapter;
Intent intencion;
RecyclerView recyclerView;
public static String source = "My Source";
public static String API_KEY = "My API Key";
SwipeRefreshLayout srl;
List<Articles> articles = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bbcnews);
srl = findViewById(R.id.swipeRefresh);
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson(source, API_KEY);
}
});
recyclerView = findViewById(R.id.recyclerView1);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter(bbcnews.this,articles);
recyclerView.setAdapter(adapter);
retrieveJson(source, API_KEY);
}
public void retrieveJson(String source, String apiKey){
srl.setRefreshing(true);
Call<Headlines> call = ApiClient.getInstance().getApi().getHeadlines(source, apiKey);
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if(response.isSuccessful() && response.body().getArticles() != null){
srl.setRefreshing(false);
articles.clear();
articles = response.body().getArticles();
adapter.setArticles(articles);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
srl.setRefreshing(false);
Toast.makeText(bbcnews.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry(){
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
public void aPerfil(View vista){
intencion = new Intent(this, profile_activity.class);
startActivity(intencion);
}
}
I don't think that I need to put the xml code with the progressbar and the swipeRefresh but here are both:
This one is the Items.xml where I created the cardView:
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:cardElevation="4dp"
android:id="#+id/cardView"
app:cardCornerRadius="10dp">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="200dp">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/loader"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/image"
android:scaleType="centerCrop"
android:src="#drawable/img"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TITLE"
android:textSize="20dp"
android:padding="10dp"
android:fontFamily="#font/g_bold"
android:textColor="#color/white"
android:id="#+id/tvTitle"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Source"
android:textSize="16dp"
android:padding="10dp"
android:ems="15"
android:fontFamily="#font/g_light"
android:textColor="#color/white"
android:id="#+id/tvSource"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/g_light"
android:gravity="right"
android:text="Date"
android:textColor="#color/white"
android:padding="10dp"
android:textSize="16dp"
android:id="#+id/tvDate"/>
</LinearLayout>
</FrameLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
And here the one with the swipeRefresh in the 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:orientation="vertical"
android:background="#color/white"
tools:context=".bbcnews">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="DINGO BBC NEWS"
android:textColor="#color/black"
android:textSize="20sp"
android:fontFamily="#font/g_bold"
android:background="#color/white"
android:padding="10dp"
android:textAlignment="center"/>
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:columnCount="2"
android:paddingLeft="20dp"
android:paddingRight="5dp"
android:background="#drawable/black_background"
android:rowCount="2">
<EditText
android:id="#+id/editTextTextPersonName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Search"
android:textColor="#color/grey"
android:textColorHint="#color/grey"
android:padding="5dp"
android:layout_column="0"
android:background="#drawable/black_background"
android:layout_row="0"
android:layout_columnWeight="1"
android:inputType="textPersonName" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="20dp"
android:background="#drawable/black_background"
android:drawableRight="#drawable/ic_baseline_search_24"
android:layout_column="1"
android:layout_row="0"/>
</GridLayout>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/swipeRefresh">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:id="#+id/recyclerView1"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</LinearLayout>
Also this is my adapter.java code:
package com.example.newsapp4;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.newsapp4.Model.Articles;
import com.squareup.picasso.Picasso;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Articles a = articles.get(position);
String imageUrl = a.getUrlToImage();
holder.tvTitle.setText(a.getTitle());
holder.tvSource.setText(a.getSource().getName());
holder.tvDate.setText(a.getPublishedAt());
Picasso.with(context).load(imageUrl).into(holder.imageView);
}
#Override
public int getItemCount() {
return articles.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle,tvSource,tvDate;
ImageView imageView;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvSource = itemView.findViewById(R.id.tvSource);
tvDate = itemView.findViewById(R.id.tvDate);
imageView = itemView.findViewById(R.id.image);
cardView = itemView.findViewById(R.id.cardView);
}
}
public void setArticles(List<Articles> articles) {
this.articles.addAll(articles);
int count = getItemCount();
notifyItemRangeInserted(count, count + articles.size());
}
}
Thanks for your time!
// Clear adapter list before add to list.
public void setArticles(List<Articles> articles) {
if(this.articles!=null && this.articles.size()>0)
this.articles.clear();
this.articles.addAll(articles);
int count = getItemCount();
notifyItemRangeInserted(count, count + articles.size());
}
From what I can understand in your code is on the success of API call after Swipe Refresh which is this section here
articles.clear();
articles = response.body().getArticles();
adapter.setArticles(articles);
You are here clearing the article inside your activity, but the thing is inside your Adapter there is already another list of articles, you are not clearing them.
And then when you make the adapter.setArticles(articles); call, inside the following function, your articles get added to the already existing list of articles and thus, the duplicate list.
public void setArticles(List<Articles> articles) {
this.articles.addAll(articles);
int count = getItemCount();
notifyItemRangeInserted(count, count + articles.size());
}
To fix this you can make the following modifications to your function.
public void setArticles(List<Articles> articles, boolean clearAll) {
if(clearAll){ this.articles.clear(); }
this.articles.addAll(articles);
notifyDataSetChanged();
}
And then modify your function call as follows
adapter.setArticles(articles, true);
That way when the Boolean is true, it will clear the existing list. Also I would suggest you to replace the insert call with data set change call. Else you can make a separate function all together for adding elements and for clearing existing elements.
problem:
Problem
if I fix:
After
I want to see AppCompatTextView with Android-Studio.
How to see the AppCompatTextView?
Nothing Error! I don't know why..
Please help this problem..
activity_searchresult.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/cfb"
tools:context=".ResultActivity">
<FrameLayout
android:id="#+id/content_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="600dp"
android:background="#color/cfb"
tools:context=".ResultActivity">
<TextView
android:id="#+id/resultText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/result_text1"
android:textColor="#color/black"
android:textSize="23sp"
android:layout_marginLeft="30dp"
app:layout_constraintBottom_toTopOf="#+id/resultText2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/resultText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/result_text2"
android:textColor="#color/black"
android:textSize="23sp"
android:layout_marginBottom="30dp"
app:layout_constraintBottom_toTopOf="#+id/resultViewPager2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ImageButton
android:id="#+id/resultFilterButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:layout_marginBottom="10dp"
android:layout_marginEnd="15dp"
android:layout_marginRight="28dp"
android:background="#color/cfb"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="#+id/dots_indicator"
app:srcCompat="#drawable/filter" />
<TextView
android:id="#+id/filterText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="25dp"
android:layout_marginRight="40dp"
android:text="#string/filter"
android:textColor="#000000"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/resultFilterButton" />
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/resultViewPager2"
android:layout_width="270dp"
android:layout_height="270dp"
android:layout_marginBottom="190dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintVertical_bias="0.3" />
<com.tbuonomo.viewpagerdotsindicator.DotsIndicator
android:id="#+id/dots_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="110dp"
app:dotsColor="#color/white"
app:dotsCornerRadius="8dp"
app:dotsSize="14dp"
app:dotsSpacing="4dp"
app:dotsWidthFactor="2.5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/resultViewPager2"
app:layout_constraintBottom_toBottomOf="parent"
app:progressMode="true"
app:selectedDotColor="#color/black" />
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="30dp"
app:layout_constraintBottom_toTopOf="#+id/resultViewPager2"
app:srcCompat="#drawable/cafebot" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ResultActivity">
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#id/navigationView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:itemTextColor="#drawable/bottom_icon_color"
app:itemIconTint="#drawable/bottom_icon_color"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="parent"
app:menu="#menu/bottom_nav" />
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
</LinearLayout>
result_item_viewpager.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:id="#+id/result_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/result_menu_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textColor="#android:color/black"
android:textSize="26sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/result_sample_image" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/result_cafe_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textColor="#android:color/black"
android:textStyle="bold"
android:textSize="23sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/result_menu_name" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/result_product_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textColor="#android:color/black"
android:textSize="22sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/result_cafe_name" />
<ImageView
android:id="#+id/result_sample_image"
android:layout_width="270dp"
android:layout_height="270dp"
android:layout_marginTop="4dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="#tools:sample/avatars" />
</androidx.constraintlayout.widget.ConstraintLayout>
ResultDataPage.java:
package com.example.myapplication;
public class ResultDataPage {
int resultImage;
String resultCafeName;
String resultMenuName;
int resultPrice;
public ResultDataPage(int image, String menuName, String cafeName, int price){
this.resultImage = image;
this.resultMenuName = menuName;
this.resultCafeName = cafeName;
this.resultPrice = price;
}
public int getImage(){
return resultImage;
}
public void setImage(int image) {
this.resultImage = image;
}
public String getMenuName(){
return resultMenuName;
}
public void setMenuName(String menuName) {
this.resultMenuName = menuName;
}
public String getCafeName() {
return resultCafeName;
}
public void setCafeName(String cafeName) {
this.resultCafeName = cafeName;
}
public int getPrice(){
return resultPrice;
}
public void setPrice(int price){
this.resultPrice = price;
}
}
ResultViewPagerAdapter.java:
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ResultViewPagerAdapter extends RecyclerView.Adapter<ResultViewHolderPage> {
private ArrayList<ResultDataPage> listData;
ResultViewPagerAdapter(ArrayList<ResultDataPage> data) {
this.listData = data;
}
#Override
public ResultViewHolderPage onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.result_item_viewpager, parent, false);
return new ResultViewHolderPage(view);
}
#Override
public void onBindViewHolder(ResultViewHolderPage holder, int position) {
if(holder instanceof ResultViewHolderPage){
ResultViewHolderPage viewHolder = (ResultViewHolderPage) holder;
viewHolder.onBind(listData.get(position));
}
}
#Override
public int getItemCount() {
return listData.size();
}
}
ResultViewHolderPage.java:
package com.example.myapplication;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
public class ResultViewHolderPage extends RecyclerView.ViewHolder {
private ImageView resultImage;
private TextView resultCafeName;
private TextView resultMenuName;
private TextView resultPrice;
ResultDataPage resultData;
ResultViewHolderPage(View itemView) {
super(itemView);
resultCafeName = itemView.findViewById(R.id.result_cafe_name);
resultImage = itemView.findViewById(R.id.result_sample_image);
resultPrice = itemView.findViewById(R.id.result_product_price);
resultMenuName = itemView.findViewById(R.id.result_menu_name);
}
public void onBind(ResultDataPage resultData){
this.resultData = resultData;
resultMenuName.setText(resultData.getMenuName());
resultCafeName.setText(resultData.getCafeName());
resultImage.setImageResource(resultData.getImage());
resultPrice.setText(Integer.toString(resultData.getPrice()).concat("원"));
}
}
ResultActivity.java:
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.tbuonomo.viewpagerdotsindicator.DotsIndicator;
import java.util.ArrayList;
public class ResultActivity extends AppCompatActivity {
// 가운데
private ViewPager2 result_ViewPager2;
private DotsIndicator dotsIndicator;
private ArrayList<ResultDataPage> list;
// 바텀네비게이션뷰
private BottomNavigationView bottomNav;
private FragmentManager fragmentManager = getSupportFragmentManager();
private SearchPage fragmentSearch = new SearchPage();
private HomePage fragmentHome = new HomePage();
private CafePage fragmentCafe = new CafePage();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchresult);
this.viewpage(); // 뷰페이저 (메뉴검색결과값)
// 바텀네비게이션
bottomNav = findViewById(R.id.navigationView);
bottomNav.setOnNavigationItemSelectedListener(new ResultActivity.ItemSelectedListener());
}
private void viewpage(){
list = new ArrayList<>();
list.add(new ResultDataPage(R.drawable.sample_1, "아메리카노","스타벅스", 4900));
list.add(new ResultDataPage(R.drawable.sample_2, "아메리카노","투썸플레이스", 4100));
list.add(new ResultDataPage(R.drawable.sample_3, "아메리카노","이디야커피", 3000));
list.add(new ResultDataPage(R.drawable.sample_3, "아메리카노","EDIYA", 3000));
list.add(new ResultDataPage(R.drawable.sample_3, "아메리카노","EDIYA", 3000));
list.add(new ResultDataPage(R.drawable.sample_3, "아메리카노","EDIYA", 3000));
list.add(new ResultDataPage(R.drawable.sample_3, "아메리카노","EDIYA", 3000));
list.add(new ResultDataPage(R.drawable.sample_3, "아메리카노","EDIYA", 3000));
list.add(new ResultDataPage(R.drawable.sample_3, "아메리카노","EDIYA", 3000));
list.add(new ResultDataPage(R.drawable.sample_3, "아메리카노","EDIYA", 3000));
result_ViewPager2 = findViewById(R.id.resultViewPager2);
result_ViewPager2.setAdapter(new ResultViewPagerAdapter(list));
dotsIndicator = findViewById(R.id.dots_indicator);
dotsIndicator.setViewPager2(result_ViewPager2);
}
//바텀네비
class ItemSelectedListener implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
switch (menuItem.getItemId()) {
case R.id.searchItem:
Intent intent1 = new Intent(getApplicationContext(), com.example.myapplication.SearchActivity.class);
startActivity(intent1);
//transaction.replace(R.id.frameLayout, fragmentSearch).commitAllowingStateLoss();
break;
case R.id.homeItem:
Intent intent2 = new Intent(getApplicationContext(), com.example.myapplication.MainActivity.class);
startActivity(intent2);
//transaction.replace(R.id.frameLayout, fragmentHome).commitAllowingStateLoss();
break;
case R.id.cafeItem:
Intent intent3 = new Intent(getApplicationContext(), com.example.myapplication.MainCflistActivity.class);
startActivity(intent3);
//transaction.replace(R.id.frameLayout, fragmentCafe).commitAllowingStateLoss();
break;
}
return true;
}
}
}
UPDATE: (Comments below for details)
At the end, text was hidden because the ViewPager was too small.
The AppCompatTextView is a retro-compatible text view for old Support Library support.
Which is your minimum supported SDK version?
You don't need this if you are using AndroidX.
However, it comes with this dependecy you have to put in your module build.gradle file:
implementation 'com.android.support:appcompat-v7:28.0.0'
After this, sync Gradle and you can use the "AppCompatTextView":
References:
https://developer.android.com/topic/libraries/support-library/packages#v7
https://developer.android.com/topic/libraries/support-library/setup#choosing
https://developer.android.com/reference/androidx/appcompat/widget/AppCompatTextView
I know that there are a lot of question like this, but i can't find one that can help me. Please pay no attention at strings that are hard coded or other things like that, i will fix. I don't see anything wrong in adapter class or in the fragments. I use Disco class for fill a place list, the Place class contains all the methods that after i use in the adapter.Can anyone help me please? Thank you.
Class MainActivity
package com.techmind.tourguideapp;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
ViewPager pager = findViewById(R.id.tourPager);
pager.setAdapter(new FragmentAdapter(manager));
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(pager);
}
}
class Disco
package com.techmind.tourguideapp;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Nahuel on 31.05.2018.
*/
public class Disco {
public static ArrayList<Places> initDiscoList(ArrayList<Places> places) {
places.add(new Places().
setAddress("via a").
setImage(1).
setName("casino").
setPhone("333").
setPrice("20€").
setHour("10:30"));
return places;
}
}
Class DiscoFragment
package com.techmind.tourguideapp;
import android.support.v4.app.Fragment;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Nahuel on 31.05.2018.
*/
public class DiscoFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<Places> list = new ArrayList<>();
list = Disco.initDiscoList(list);
PlacesAdapter adapter = new PlacesAdapter(getActivity(), list);
View view = inflater.inflate(R.layout.row_item, container, false);
ListView listView = (ListView) view.findViewById(R.id.list_items);
listView.setAdapter(adapter);
return view;
}
}
Class FragmentAdapter
package com.techmind.tourguideapp;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by Nahuel on 31.05.2018.
*/
public class FragmentAdapter extends FragmentPagerAdapter {
public FragmentAdapter (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new DiscoFragment();
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position) {
return "Gradara";
}
}
Class Places
package com.techmind.tourguideapp;
/**
* Created by Nahuel on 31.05.2018.
*/
public class Places {
private String name;
private String price;
private String phone;
private String Address;
private String hour;
private int image;
private final int NO_IMAGE = -1;
public Places () {
}
public String getHour() {
return hour;
}
public String getName() {
return name;
}
public String getPrice() {
return price;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return Address;
}
public int getImage() {
return image;
}
public Places setName(String name) {
this.name = name;
return this;
}
public Places setHour(String hour) {
this.hour = hour;
return this;
}
public Places setPrice(String price) {
this.price = price;
return this;
}
public Places setPhone(String phone) {
this.phone = phone;
return this;
}
public Places setAddress(String address) {
Address = address;
return this;
}
public Places setImage(int image) {
this.image = image;
return this;
}
}
Class PlaceAdapter
package com.techmind.tourguideapp;
import android.content.Context;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class PlacesAdapter extends ArrayAdapter<Places> {
public PlacesAdapter(Context context, List<Places> places) {
super(context,-1, places);
}
public View getView (int position, ViewGroup parent, View convertView) {
View listView = convertView;
Places place = getItem(position);
if(listView == null) {
listView = LayoutInflater.from(getContext()).inflate(
R.layout.row_item, parent, false);
}
TextView location = listView.findViewById(R.id.locationName);
location.setText("casino");
TextView hour = listView.findViewById(R.id.txthour);
hour.setText("aaa");
TextView address = listView.findViewById(R.id.address);
address.setText("aaaaa");
TextView price = listView.findViewById(R.id.txtmoney);
price.setText("aaaaa");
TextView phone = listView.findViewById(R.id.phone);
phone.setText("aaaaa");
ImageView img = listView.findViewById(R.id.imgRow);
img.setImageResource(R.drawable.ic_launcher_background);
return listView;
}
}
Activity_Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.techmind.tourguideapp.MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
/>
<android.support.v4.view.ViewPager
android:id="#+id/tourPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
List_item.xml
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list_items"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
Row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imgRow"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:src="#drawable/gradara" />
<TextView
android:id="#+id/locationName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="24sp"
android:textStyle="bold"
android:text=""/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="0.5">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<ImageView
android:id="#+id/positionIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#mipmap/position"
android:layout_alignParentStart="true"/>
<TextView
android:id="#+id/txtPosition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/positionIcon"
android:layout_marginTop="5dp"
android:text="" />
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/positionIcon"
android:layout_toRightOf="#id/positionIcon"
android:text="" />
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<ImageView
android:id="#+id/moneyIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#mipmap/money"
android:layout_alignParentStart="true"/>
<TextView
android:id="#+id/txtmoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/moneyIcon"
android:layout_marginTop="15dp"
android:text="10€ - 20€" />
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<ImageView
android:id="#+id/hourIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:src="#mipmap/hour"
android:layout_alignParentStart="true"/>
<TextView
android:id="#+id/txthour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/hourIcon"
android:layout_marginTop="15dp"
android:text="09:30 - 23:00" />
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone:"
android:layout_marginEnd="5dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3334323560"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
You said you got a null pointer on set adapter. Are you talking about
this line in file DiscoFragment?
listView.setAdapter(adapter)
if listView is null then the findViewByID didn't find a view. Or maybe something inside adapter is null. It is hard to tell from what you said.
i found the error in
ArrayList<Places> list = new ArrayList<>();
list = Disco.initDiscoList(list);
PlacesAdapter adapter = new PlacesAdapter(getActivity(), list);
View view = inflater.inflate(R.layout.row_item, container, false);
ListView listView = (ListView) view.findViewById(R.id.list_items);
listView.setAdapter(adapter);
return view;
}
When i use the inflate method the first parameter was wrong, i used the layout of the row instead of the listView layout.
Thank you for your answers, next times i will post logs and less useless code :)