I am getting data from TMDB API and displaying it on screen.
Right now, I am trying to get reviews from that API.
Everything seems fine, I created: adapter,model,interface,xml and activities, but it is not displaying any data.
API is working fine, I can see from Android Monitor that I am getting right data.
Somebody help, please.
Bellow is my DetailsActivity where I am trying to fetch data:
public class MovieDetailActivity extends AppCompatActivity {
public static final String EXTRA_MOVIE = "EXTRA_MOVIE";
private Movie mMovie;
private Reviews mReviews;
private Genres mGenres;
public ReviewAdapter rAdapter;
ImageView backdrop;
ImageView poster;
TextView title;
TextView description;
TextView releaseDate;
TextView voteAverage;
RecyclerView reviews;
TextView content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
if (getIntent().hasExtra(EXTRA_MOVIE)) {
mMovie = getIntent().getParcelableExtra(EXTRA_MOVIE);
} else {
throw new IllegalArgumentException("Detail activity must receive a movie parcelable");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
CollapsingToolbarLayout toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
toolbarLayout.setTitle(mMovie.getTitle());
reviews = (RecyclerView) findViewById(R.id.recyclerView2);
reviews.setLayoutManager(new LinearLayoutManager(this));
rAdapter = new ReviewAdapter(MovieDetailActivity.this);
reviews.setAdapter(rAdapter);
getReviews(mMovie.getId());
poster = (ImageView) findViewById(R.id.movie_poster);
String internetUrl = "http://image.tmdb.org/t/p/w500";
Glide.with(this)
.load(mMovie.getPoster())
.into(poster);
Glide.with(this)
.load(mMovie.getBackdrop())
.into(backdrop);
}
private void getReviews(Integer id) {
RestAdapter.getMovieService().getReviews(id, new Callback<ReviewWraper>() {
#Override
public void success(ReviewWraper reviewWraper, Response response) {
rAdapter.setReviewList(reviewWraper.getResults());
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
public static class MovieViewHolder extends RecyclerView.ViewHolder {
public ImageView reviewPicture;
public TextView reviewUsername;
public TextView reviewDate;
public TextView reviewTime;
public TextView reviewComment;
public MovieViewHolder(View itemView) {
super(itemView);
reviewPicture = (ImageView) itemView.findViewById(R.id.picture_review);
reviewUsername = (TextView) itemView.findViewById(R.id.username_review);
reviewDate = (TextView) itemView.findViewById(R.id.date_review);
reviewTime = (TextView) itemView.findViewById(R.id.time_review);
reviewComment = (TextView) itemView.findViewById(R.id.review_comment);
}
}
Here is my adapter class:
public class ReviewAdapter extends RecyclerView.Adapter<MovieDetailActivity.MovieViewHolder> {
private List<Reviews> rReviewList;
private LayoutInflater rInflater;
private Context rContext;
public ReviewAdapter(Context context) {
this.rContext = context;
this.rInflater = LayoutInflater.from(context);
this.rReviewList = new ArrayList<>();
}
public MovieDetailActivity.MovieViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
// create a new view
View view = rInflater.inflate(R.layout.row_review, parent, false);
return new MovieDetailActivity.MovieViewHolder(view);
}
#Override
public void onBindViewHolder(MovieDetailActivity.MovieViewHolder holder, int position) {
Reviews reviews = rReviewList.get(position);
Picasso.with(rContext)
.load(reviews.getUrl())
.into(holder.reviewPicture);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Perform click
}
});
}
#Override
public int getItemCount() {
return rReviewList.size();
}
//To update data
public void setReviewList(List<Reviews> reviewsList) {
this.rReviewList = new ArrayList<>();
this.rReviewList.addAll(reviewsList);
notifyDataSetChanged();
}
Bellow is XML 1:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/picture_review"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:adjustViewBounds="true"
android:id="#+id/username_review"
android:layout_width="40dp"
android:layout_height="20dp"
android:width="20dp"
android:height="20dp"
android:textColor="#ffffff" />
<TextView
android:id="#+id/date_review"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textColor="#ffffff" />
<TextView
android:id="#+id/time_review"
android:layout_width="10dp"
android:layout_height="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#ffffff" />
<TextView
android:id="#+id/review_comment"
android:layout_width="250dp"
android:layout_height="250dp"
android:textColor="#ffffff"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/picture_review"
android:layout_toEndOf="#+id/picture_review" />
</RelativeLayout>
And XML 2 with RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.demo.mtin.mtin.MovieDetailActivity"
tools:showIn="#layout/activity_movie_detail">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ffffff" />
Try to give fixed height instead of "wrap_content" on your row in root of Xml 1.
tools:showIn="#layout/activity_movie_detail">
If XML 2 needs to show in XML 1, XML1 must have this -
<include layout="#layout/XML2"/>
See this for more details -
android-how-to-use-tools-with-include-layout
Related
I tried the solutions on the other similar posts that I found here but they did not help me. I hope someone can help.
I get data from Unsplash's API and the ArrayList contains 10 items once I get a response, that's why I think It has to be something with the way the view is inflated.
This is code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "unsplash";
private final String CLIENT_ID = "...myclientID...";
// testing keyword used on the API to search for pictures
private final String KEYWORD = "stackOverflow";
private final String urlBase = "https://api.unsplash.com/";
private Retrofit retrofit;
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder()
.baseUrl(urlBase)
.addConverterFactory(GsonConverterFactory.create())
.build();
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerViewAdapter = new RecyclerViewAdapter();
recyclerView.setAdapter(recyclerViewAdapter);
getData();
}
private void getData() {
PictureService service = retrofit.create(PictureService.class);
Call<PictureResponse> pictureResponseCall = service.getPictureList(KEYWORD, CLIENT_ID);
pictureResponseCall.enqueue(new Callback<PictureResponse>() {
#Override
public void onResponse(Call<PictureResponse> call, Response<PictureResponse> response) {
if (response.isSuccessful()){
PictureResponse pictureResponse = response.body();
ArrayList<UnsplashPic> pictureList = pictureResponse.getResults();
recyclerViewAdapter.addPictures(pictureList);
}else{
Log.e (TAG, " onResponse " + response.errorBody());
}
}
#Override
public void onFailure(Call<PictureResponse> call, Throwable t) {
Log.e (TAG, " onFailure " + t.getMessage());
}
});
}
}
My adapter class:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UnsplashPic> pictureList;
public RecyclerViewAdapter (){
pictureList = new ArrayList<>();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_view_holder, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
UnsplashPic pic = pictureList.get(i);
viewHolder.artistName.setText(pic.user.getUsername());
viewHolder.unsplash.setText("Unsplash");
}
#Override
public int getItemCount() {
return pictureList.size();
}
public void addPictures(ArrayList<UnsplashPic> pictureList) {
pictureList.addAll(pictureList);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView artistName;
private TextView unsplash;
public ViewHolder (View itemView){
super(itemView);
imageView = itemView.findViewById(R.id.imageview);
artistName = itemView.findViewById(R.id.artist_name);
unsplash = itemView.findViewById(R.id.unsplash_name);
}
}
}
item_view_holder.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageview"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="#ababab"
android:contentDescription="unsplash picture" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Photo by "/>
<TextView
android:id="#+id/artist_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="on "/>
<TextView
android:id="#+id/unsplash_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true" />
</LinearLayout>
activity_main.xml
<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=".MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Search for pictures"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerview">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Here:
public void addPictures(ArrayList<UnsplashPic> pictureList) {
pictureList.addAll(pictureList);
notifyDataSetChanged();
}
you are actually adding the content of the pictureList you send as parameter of the function to that same list, your list from adapter is not updated.
You should do like this instead:
public void addPictures(ArrayList<UnsplashPic> pictureList) {
this.pictureList.addAll(pictureList);
notifyDataSetChanged();
}
I have created RecyclerView and showing data from JSON.
Issue I'm facing is, while Toast data is showing correctly, but in RecyclerView same data is not appear.
Here is code:
public class MainActivity extends AppCompatActivity {
private static final int NUM_LIST_ITEMS = 100;
private static final String TOKEN =
"71cf2d3dec294394e267fbb0bf28916f4198f8d6";
private CuloAdapter culoAdapter;
List<Hotel> lh = new ArrayList<>();
RecyclerView recyclerView;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.rv_tiketapi);
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layout);
CuloAdapter ar = new CuloAdapter(lh);
recyclerView.setAdapter(ar);
loadHotelLocation();
}
private void loadHotelLocation() {
final search apiService = ApiService.getService(search.class);
retrofit2.Call<SingleResult<Hotel>> call = apiService.findHotel(TOKEN,
"json");
call.enqueue(new Callback<SingleResult<Hotel>>() {
#Override
public void onResponse(retrofit2.Call<SingleResult<Hotel>> call,
Response<SingleResult<Hotel>> response) {
if (response.body().getDiagnostic().isSuccess()) {
//SingleResult.ResultList list =
response.body().getResults();
List<Hotel> mHotels = (List<Hotel>)
response.body().getResults().getResult();
lh.addAll(mHotels);
Toast.makeText(getApplicationContext(), "OK" +lh,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(retrofit2.Call<SingleResult<Hotel>> call,
Throwable t) {
}
});
}
RecyclerView Adapter :
public class CuloAdapter extends
RecyclerView.Adapter<CuloAdapter.ViewHolder> {
public CuloAdapter(List<Hotel> lh) {
this.items = lh;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtTitle;
public TextView txtSubTitle;
public ImageView imgIcon;
public ViewHolder(final View container) {
super(container);
txtTitle = (TextView) container.findViewById(R.id.airportName);
txtSubTitle = (TextView) container.findViewById(R.id.airportCode);
}
}
private List<Hotel> items;
public CuloAdapter(final Activity activity, List<Hotel> items) {
this.items = items;
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public void onBindViewHolder(CuloAdapter.ViewHolder holder, int position) {
Hotel item = items.get(position);
holder.txtTitle.setText(item.getLabel());
holder.txtSubTitle.setText(item.getId());
}
#Override
public CuloAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_flight, parent, false);
return new ViewHolder(v);
}
}
MainActivity 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.example.admin.exampletiketapi.MainActivity">
<EditText
android:id="#+id/et_find"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_tiketapi"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Item List XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/airportsLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp">
<TextView
android:id="#+id/airportName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:text="Soekarno Hatta" />
<TextView
android:id="#+id/airportCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:text="20" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="5dp"
android:background="#DDD"
android:visibility="visible" />
</LinearLayout>
In your code you are trying to set adapter before loading data.
CuloAdapter ar = new CuloAdapter(lh);
recyclerView.setAdapter(ar);
loadHotelLocation();
What i found is You are getting data in loadHotelLocation(), but trying to set adpter before that,
Call notifyDatasetChanged after lh.addAll(mHotels). And check for null's else you are heading for crash in case search results are zero/null
Everytime we open the activity that bares the recycler adapter it fails to load on the first try. Exiting the activity and re-entering fixes the problem. Here is a gif for example. https://gyazo.com/32dc664dd427ef1129704a09861a3708
The Item i am spawning in:
<?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:card_view="http://schemas.android.com/tools"
android:id="#+id/show_chat_single_item_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="70dp"
app:cardBackgroundColor="#dcdada"
app:cardCornerRadius="0dp"
app:contentPadding="3dp"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="2dp"
card_view:cardUseCompatPadding="true">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/chat_persion_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/chat_persion_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="0dp"
android:text="Name"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintLeft_toRightOf="#+id/chat_persion_image"
app:layout_constraintTop_toTopOf="#+id/chat_persion_image" />
<TextView
android:id="#+id/chat_persion_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginTop="8dp"
android:text="Email"
app:layout_constraintLeft_toLeftOf="#+id/chat_persion_name"
app:layout_constraintTop_toBottomOf="#+id/chat_persion_name" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
My conversation layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/msgs_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:theme="#style/AppTheme2"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/active_chats"
android:layout_width="match_parent"
android:layout_height="510dp"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="57dp">
</android.support.v7.widget.RecyclerView>
<include
android:id="#+id/include2"
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
My Adapter:
public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder>
{
private ArrayList<User> mUsers;
private Context mContext;
public ActiveChatConvo(ArrayList<User> photos,Context dick) {
mUsers = photos;
mContext = dick;
}
private Context getContext() {
return mContext;
}
#Override
public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Get the data model based on position
User user = mUsers.get(position);
// Set item views based on your views and data model
TextView name = holder.mItemName;
name.setText(user.getName());
TextView description = holder.mItemDescription;
description.setText(user.getEmail());
ImageView pic = holder.mItemImage;
Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);
}
#Override
public int getItemCount() {
return mUsers.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mItemImage;
private TextView mItemName;
private TextView mItemDescription;
private LinearLayout layout;
final LinearLayout.LayoutParams params;
public ViewHolder(View v) {
super(v);
mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Context context = itemView.getContext();
Intent showChatIntent = new Intent(context, ChatConversationActivity.class);
//showPhotoIntent.putExtra(PHOTO_KEY, mPhoto);
context.startActivity(showChatIntent);
}
}
}
My main class
public class ConnectionsActivity extends AppCompatActivity {
private Toolbar toolbar;
private ViewPager mViewPager;
private TextView person_name,person_email;
private RecyclerView recyclerView;
private DatabaseReference mRef;
private LinearLayoutManager mLinearLayoutManager;
private ArrayList<User> users;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connections);
//Database
mRef = FirebaseDatabase.getInstance().getReference("Users");
mRef.keepSynced(true);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
users = new ArrayList<>();
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String name = postSnapshot.child("Name").getValue(String.class);
String email = postSnapshot.child("Email").getValue(String.class);
String pic = postSnapshot.child("image").getValue(String.class);
users.add(new User(name,email,pic));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Recycler View
recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
recyclerView.setAdapter(adapter);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
//VIEWS
toolbar = (Toolbar) findViewById(R.id.tToolbar);
if (toolbar != null)
setSupportActionBar(toolbar);
ImageView profileActivity = (ImageView) toolbar.findViewById(R.id.action_profile);
ImageView homeActivity = (ImageView) toolbar.findViewById(R.id.action_home);
profileActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileActivity = new Intent(ConnectionsActivity.this, ProfileActivity.class);
startActivity(profileActivity);
finish();
overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
});
homeActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent home = new Intent(ConnectionsActivity.this, HomeActivity.class);
startActivity(home);
finish();
overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
});
}
}
So if the recyclerView Activity is the first activity I visit then it will not create the items.
Firebase is synchronize so it doesn't block the main thread of your application, that mean that your application continue executing, you need to notify the adapter after firebase finishing his job by using adapter.notifiyDatasetChanged() after the for loop
Replace this:
recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
recyclerView.setAdapter(adapter);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
with this:
recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
recyclerView.setAdapter(adapter);
You need to set adapter after you set LayoutManager.
In my case I managed to solve it I found a way to start FirebaseDatabase before opening the activity and added the cod
adapter.notifyDataSetChanged();
and then I started the firebase before opening it with this
FirebaseDatabase.getInstance().getReference().keepSynced(true);
You can use Boolean button to check if it is true adapter is made
I am trying to make a simple horizontal recyclerview with images and some text etc.
But for some reason, the images are switcing around and ending up in the wrong places when I scroll back and forth.
The problem lies, without a doubt in the adapter:
public class SponsoredAdvertsAdapter extends RecyclerView.Adapter<SponsoredAdvertsAdapter.SponsoredAdvertHolder> {
private Context context;
private List<CustomAdvert> adverts;
private boolean isBigScreen;
public SponsoredAdvertsAdapter(Context context, List<CustomAdvert> adverts) {
this.context = context;
this.adverts = adverts;
isBigScreen = ScreenUtil.isBigScreen(context);
}
#Override
public SponsoredAdvertsAdapter.SponsoredAdvertHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_search_popular_adverts_phone, null);
if (isBigScreen) {
layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_search_popular_adverts_tablet, null);
}
return new SponsoredAdvertHolder(layoutView);
}
#Override
public void onBindViewHolder(final SponsoredAdvertHolder holder, int position) {
final CustomAdvert advert = adverts.get(position);
String title = advert.getAdvert().getValidTextShort();
holder.title.setText(title);
holder.unreadBadge.setText(context.getString(R.string.customer_tilbudsaviser_unread_advert));
if (advert.isRead()) {
holder.unreadBadge.setVisibility(View.INVISIBLE);
} else {
holder.unreadBadge.setVisibility(View.VISIBLE);
}
if (holder.image != null) {
attachAdvertImage(holder.image, holder.imageView);
} else {
String logoUrl = ImageScaleUrlBuilder.getFixedWidthUrl(advert.getLogoUrl(), holder.imageView.getMeasuredWidth());
ImageLoaderHelper.loadImageFromUrl(logoUrl, new ImageLoaderHelper.ImageLoadedCallback() {
#Override
public void onBitmapLoaded(Bitmap bitmap) {
holder.image = bitmap;
attachAdvertImage(bitmap, holder.imageView);
}
});
}
AdvertActivity.startAdvertActivity(context, advert.getCustomer(), advert.getAdvert(), 0, null);
}
private void attachAdvertImage(final Bitmap image, final ImageView imageView) {
RunOnUIThread.post(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(image);
}
});
}
#Override
public int getItemCount() {
return adverts.size();
}
public class SponsoredAdvertHolder extends RecyclerView.ViewHolder {
private final View container;
private final ImageView imageView;
private final TextView title, unreadBadge;
private Bitmap image;
public SponsoredAdvertHolder(View itemView) {
super(itemView);
container = itemView.findViewById(R.id.item_search_popular_adverts_container);
imageView = (ImageView) itemView.findViewById(R.id.search_popular_advert_imageview);
title = (TextView) itemView.findViewById(R.id.search_popular_advert_title);
unreadBadge = (TextView) itemView.findViewById(R.id.unread_badge);
}
}
}
Here is the code where I set the adapter to the recyclerview:
sponsoredAdvertsAdapter = new SponsoredAdvertsAdapter(getContext(), adverts);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
sponsoredAdvertsRecyclerView.setLayoutManager(linearLayoutManager);
sponsoredAdvertsRecyclerView.setAdapter(sponsoredAdvertsAdapter);
And here is the recyclerview (xml):
<LinearLayout
android:id="#+id/popular_searches_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:background="#color/white">
<android.support.v7.widget.RecyclerView
android:id="#+id/popular_adverts_searches_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
And the xml for the item:¨
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:id="#+id/item_search_popular_adverts_container">
<ImageView
android:id="#+id/search_popular_advert_imageview"
android:layout_width="136dp"
android:layout_height="170dp"
android:gravity="bottom"
android:scaleType="fitXY"
android:layout_marginBottom="10dp"
android:layout_gravity="center_horizontal"/>
<TextView
android:id="#+id/search_popular_advert_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#color/secondary_grey"
android:textSize="14sp"
android:text="Title"/>
<include
android:id="#+id/unread_badge"
layout="#layout/item_badge"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="3dp"
android:text="#string/customer_tilbudsaviser_unread_advert"
android:visibility="invisible" />
</LinearLayout>
I know that this is a fairly common problem with Recyclerviews, but even after looking at other solutions, I can't seem to get my solution to work.
Im suggesting you to use an image library like Glide (git link) to display with image view. it will cache the images properly and show. this may fix the issue ;)
use glide by replacing this line
imageView.setImageBitmap(image);
to
Glide
.with(myFragment)
.load(bitmap)
.centerCrop()
.crossFade()
.into(myImageView);
I want to create a list of items that have a background image and a TextView. Although it creates the RecyclerView normally and sets the text, the background image doesn't set.
This is my Adapter Class
public class Casino_Adapter extends RecyclerView.Adapter<Casino_Adapter.ViewHolder> {
private Data[] mDataset;
private ClickListener clickListener;
public Context context;
// Provide a suitable constructor (depends on the kind of dataset)
public Casino_Adapter(Data[] myDataset) {
this.mDataset = myDataset;
this.context = context;
}
#Override
public Casino_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.casino_card_row, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final Context context = null;
// each data item is just a string in this case
public TextView mTextView;
public ImageView mImageView;
public CardView cardView;
//Typeface tf;
public ViewHolder(View v) {
super(v);
mTextView = (TextView) v.findViewById(R.id.text);
mImageView = (ImageView) v.findViewById(R.id.image);
cardView = (CardView) v.findViewById(R.id.card_view);
//cardView.setPreventCornerOverlap(false);
}
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(mDataset[position].getText());
holder.mImageView.setImageResource(mDataset[position].getImage());
}
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
public interface ClickListener {
public void itemClicked(View view, int pos);
}
}
I have a Fragment Class where I want the RecyclerView to be.
public class CasinoFragment extends Fragment {
protected RecyclerView recyclerView;
protected RecyclerView.Adapter mAdapter;
protected RecyclerView.LayoutManager mLayoutManager;
public CasinoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initial();
}
private void initial() {
final Data datas[] =
{
new Data("This is an item", R.drawable.ic_home_white_36dp),
new Data("This is an item 2", R.drawable.car),
new Data("asdasd`sdads", R.drawable.car),
new Data("This is an item 3", R.drawable.car)
};
mAdapter = new Casino_Adapter(datas);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_casino, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAdapter);
return view;
}
}
And these are the Setters that I use.
public class Data {
int image;
String text;
public Data(String title, int backimage)
{
this.text = title;
this.image = backimage;
}
public String getText()
{
return text;
}
public int getImage()
{
return image;
}
public void setText()
{
this.text=text;
}
public void setImageID()
{
this.image = image;
}
}
Casino Row XML
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="8dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#111111"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/image"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:background="#drawable/image_round"
android:src="#drawable/car" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/image"
android:id="#+id/rel_color"
android:background="#4c4c4c">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Μπύρα"
android:textColor="#fcfcfc"
android:textSize="30sp"
android:shadowColor="#000000"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="5"
android:id="#+id/text"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
The result I get is the following.
The reason why you aren't seeing your image, is because it isn't actually visible.
Your rel_color layout has the same size attributes as your ImageView.
If you want to display a layout above the ImageView, you just need to remove the background of it, otherwise the ImageView will be hidden.
Just Like that. but remember your images dimensions must be low. in my case i used 200x200
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/rl_menu_item"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_margin="5dp"
android:background="#android:color/transparent"
card_view:cardCornerRadius="4dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:id="#+id/img_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_blrr">
<ImageView
android:id="#+id/iv_icon"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"
android:adjustViewBounds="true"
android:background="#drawable/gray_circle"
android:padding="15dp"
android:scaleType="centerCrop"
android:src="#drawable/school" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#id/iv_icon"
android:layout_alignLeft="#id/iv_icon"
android:layout_alignRight="#id/iv_icon"
android:layout_alignStart="#id/iv_icon"
android:layout_below="#id/iv_icon"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Your Favourite Place"
android:textColor="#android:color/black" />
</RelativeLayout>
</android.support.v7.widget.CardView>