This question already has answers here:
RecyclerView adapter show only first item
(3 answers)
Closed 3 years ago.
I use recycler view before and i never have this problems. The principal difference between the other recycler views that i made is that i use SQLite for this one.
I want all the items appears one between other and without white spaces between them.
LEADER BOARD ACTIVITY WHERE I INITIALIZE MY RECYCLER
public class LeaderBoard extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerController mAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leader_board);
DaoSQLite manager=new DaoSQLite(this);
SQLiteDatabase db=manager.getReadableDatabase();
layoutManager=new LinearLayoutManager(this);
recyclerView=findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
mAdapter=new RecyclerController(manager.getSortScores());
recyclerView.setAdapter(mAdapter);
}
}
VIEW FOR RECYCLER
<?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/txtNameOption"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/lbName"
android:layout_width="129dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="16dp"
android:layout_marginTop="21dp"
android:fontFamily="serif"
android:text="Name"
android:textAlignment="textStart"
android:textAppearance="#style/TextAppearance.AppCompat.Display2"
android:textIsSelectable="false"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/lbLevel2"
android:layout_width="109dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="154dp"
android:layout_marginTop="21dp"
android:fontFamily="serif"
android:text="Level"
android:textAlignment="textStart"
android:textAppearance="#style/TextAppearance.AppCompat.Display2"
android:textIsSelectable="false"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/lbScore"
android:layout_width="132dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="266dp"
android:layout_marginTop="21dp"
android:fontFamily="serif"
android:text="Score"
android:textAlignment="textStart"
android:textAppearance="#style/TextAppearance.AppCompat.Display2"
android:textIsSelectable="false"
android:textSize="15sp"
android:textStyle="bold" />
<View
android:id="#+id/view"
android:layout_width="wrap_content"
android:layout_height="79dp"
android:background="#604697"
android:backgroundTint="#34BE3838"
android:backgroundTintMode="src_in"
android:hapticFeedbackEnabled="false" />
</RelativeLayout>
THIS IS THE SQLite DAO
package com.example.quizappjava.DataBase;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.quizappjava.Beans.User;
public class DaoSQLite extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Game.db";
private static final String TABLE_NAME_SCORES = "puntuaciones";
private SQLiteDatabase sqLiteDatabase = getWritableDatabase();
public DaoSQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+ TABLE_NAME_SCORES +" (_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT (15) NOT NULL,score INTEGER NOT NULL, level INTEGER NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getSortScores(){
return getReadableDatabase().query(TABLE_NAME_SCORES,null,null,null,null,null,"score");
}
public void insertNewScore(User user){
sqLiteDatabase.insert(TABLE_NAME_SCORES,null,user.toContentValues());
}
}
RECYCLER CONTROLLER
package com.example.quizappjava.JavaClasses;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.quizappjava.Beans.User;
import com.example.quizappjava.R;
import java.util.ArrayList;
public class RecyclerController extends RecyclerView.Adapter<RecyclerController.ViewHolder> {
private ArrayList<User> userArraList = new ArrayList<User>();
public RecyclerController(Cursor queryRequest) {
ParseData(queryRequest);
}
private void ParseData(Cursor queryRequest) {
for (queryRequest.moveToFirst(); !queryRequest.isAfterLast(); queryRequest.moveToNext()) {
userArraList.add(
new User(
queryRequest.getString(queryRequest.getColumnIndex("name")),
queryRequest.getInt(queryRequest.getColumnIndex("score")),
queryRequest.getInt(queryRequest.getColumnIndex("level"))
));
}
}
#NonNull
#Override
public RecyclerController.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerController.ViewHolder holder, int position) {
holder.user=userArraList.get(position);
holder.lbName.setText(userArraList.get(position).getName());
holder.lbScore.setText(userArraList.get(position).getScore()+"");
holder.lbLevel.setText(userArraList.get(position).getLevel()+"");
}
#Override
public int getItemCount() {
return userArraList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView lbName;
private TextView lbScore;
private TextView lbLevel;
private User user;
public ViewHolder(#NonNull View itemView) {
super(itemView);
lbName=itemView.findViewById(R.id.lbName);
lbLevel=itemView.findViewById(R.id.lbLevel2);
lbScore=itemView.findViewById(R.id.lbScore);
}
}
}
This images shows how i see the leader board when i execute the app, the first image is how i see one item and the second one is the blank space between both items
Try
edit this :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/txtNameOption"
android:layout_width="match_parent"
android:layout_height="match_parent">
To:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/txtNameOption"
android:layout_width="match_parent"
android:layout_height="wrap_content">
You should have the same problem explained and resolved here.
The Relative Layout passed to your Recycler has android:layout_height="match_parent, but should have android:layout_height="wrap_content, otherwhise every item will be height as much as RecylerView is.
You have to adjust your recyclerview's cell height to wrap content instead of match parent:
VIEW FOR RECYCLER
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/txtNameOption"
android:layout_width="match_parent"
android:layout_height="wrap_content">
match_parent height would scale the cell to the height of the parent view
Related
I have a NewsDetailsActivity file that is displaying some news details. On top of the news details I want to display some cardview in a recyclerview. The recyclerView is not showing up but the worse part is that another recyclerview (that I have in the MainActivity is showing up in my NewsDetailsActivity like if If I am calling some id from my NewsDetailsActivity.
The only thing I want is to display some information on the top of the news details using the the recyclerview id my_recycler_view_coin_details
NewsDetailsActivity
package com.noticripto.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.noticripto.APIClientCoin;
import com.noticripto.adapters.CryptoListAdapter;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.noticripto.MainActivity;
import com.noticripto.R;
import com.noticripto.adapters.NewsAdapter;
import com.noticripto.model.HomePageModel;
import com.noticripto.rest.ApiClient;
import com.noticripto.rest.ApiInterface;
import com.noticripto.retrofit.CryptoList;
import com.noticripto.retrofit.Datum;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class NewsDetailActivity extends AppCompatActivity {
Toolbar toolbar;
TextView sourceName, newsTitle, newsDesc, newsDate, newsView,labelSimilar;
Button viewMore;
ImageView imagy,small_icn;
ProgressBar progressBar;
RecyclerView recyclerView3;
CryptoListAdapter adapterCoin2;
ApiInterface apiInterfaceCoin2;
List<Datum> cryptoList2 = null;
HomePageModel.News detailNews = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_detail);
apiInterfaceCoin2 = APIClientCoin.getClient().create(ApiInterface.class);
recyclerView3 = findViewById(R.id.my_recycler_view_coin_details);
initViews();
LoadNewsDetails();
getCoinList();
}
private void LoadNewsDetails() {
// Calling our api
ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Map<String, String> params = new HashMap<>();
params.put("id" , getIntent().getIntExtra("pid", 0) + "");
Call<HomePageModel> call = apiInterface.getNewsDetailsById(params);
call.enqueue(new Callback<HomePageModel>() {
#Override
public void onResponse(Call<HomePageModel> call, Response<HomePageModel> response) {
// Update the news layout
detailNews = response.body().getNews().get(0);
newsTitle.setText(detailNews.getTitle());
newsDesc.setText(NewsAdapter.removeHtml(detailNews.getPostContent()));
if (detailNews.getImage().length() >=1){
Glide.with(NewsDetailActivity.this)
.load(detailNews.getImage())
.placeholder(R.drawable.image1)
.into(imagy);
}else{
imagy.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<HomePageModel> call, Throwable t) {
progressBar.setVisibility(View.GONE);
}
});
}
private void initViews() {
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
toolbar.setNavigationIcon(R.drawable.icon_arrow_back_white);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
cryptoList2 = new ArrayList<>();
adapterCoin2 = new CryptoListAdapter(cryptoList2);
// sourceName = findViewById(R.id.source_name );
newsTitle = findViewById(R.id.news_title);
newsDesc = findViewById(R.id.news_desc);
newsDate = findViewById(R.id.news_date);
//newsView = findViewById(R.id.news_view);
labelSimilar = findViewById(R.id.label_similar_news);
//viewMore = findViewById(R.id.view_more);
progressBar = findViewById(R.id.progressBar);
imagy =findViewById(R.id.news_image);
//small_icn = findViewById(R.id.small_icn);
recyclerView3 = findViewById(R.id.my_recycler_view_coin_details);
LinearLayoutManager linearLayoutManager3 =new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView3.setLayoutManager(linearLayoutManager3);
recyclerView3.setNestedScrollingEnabled(false);
recyclerView3.setAdapter(adapterCoin2);
adapterCoin2.notifyItemInserted(0);
recyclerView3.scrollToPosition(0);
}
public void getCoinList() {
Call<CryptoList> call2 = apiInterfaceCoin2.doGetUserList("20");
call2.enqueue(new Callback<CryptoList>() {
#Override
public void onResponse(Call<CryptoList> call, Response<CryptoList> response)
{
CryptoList list = response.body();
cryptoList2.clear();
cryptoList2.addAll(list.getData());
adapterCoin2.notifyDataSetChanged();
System.out.println("List getData = " + list.getData());
}
#Override
public void onFailure(Call<CryptoList> call, Throwable t) {
Toast.makeText(NewsDetailActivity.this, "onFailure",
Toast.LENGTH_SHORT).show();
Log.d("XXXX", t.getLocalizedMessage());
call.cancel();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.news_details_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.share){
if (detailNews != null){
// Opening sharing options
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, detailNews.getTitle());
i.putExtra(Intent.EXTRA_TEXT, detailNews.getPostContent());
startActivity(i);
}else{
Toast.makeText(this, "Lo Sentimos!", Toast.LENGTH_SHORT).show();
}
}
return super.onOptionsItemSelected(item);
}
}
crypto_list_item_in_detail_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardViewCoinDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
app:cardCornerRadius="8dp"
app:cardBackgroundColor="#android:color/white">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/symbolNameDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="roboto_bold"
android:gravity="center"
android:paddingBottom="3dp"
android:singleLine="true"
android:text="Symbol"
android:textAppearance="#android:style/TextAppearance.Large"
android:textColor="#000"
android:textSize="15dp" />
<TextView
android:id="#+id/priceDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textStyle="bold"
android:text="Price"
android:textSize="13dp"
android:layout_marginBottom="5dp"
android:layout_toRightOf="#+id/symbolNameDetails"
android:textAppearance="#android:style/TextAppearance.Medium"
android:textColor="#000" />
</RelativeLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
activity_news_details.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.NewsDetailActivity">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbar"
android:background="#color/black"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_below="#+id/toolbar"
android:layout_height="wrap_content">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:indeterminateTint="#color/yellow"/>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
android:overScrollMode="never"
android:layout_below="#+id/progressBar">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/my_recycler_view_coin_details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="horizontal" />
<androidx.cardview.widget.CardView
android:id="#+id/wrapper_cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/wrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/news_title"
android:text="Titulo"
android:textStyle="bold"
android:layout_below="#+id/wrapper"
android:textSize="22sp"
android:paddingLeft="16dp"
android:textAlignment="center"
android:paddingStart="16dp"
android:textColor="#color/black"
android:gravity="center_horizontal" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/wrapper_news"
android:layout_below="#id/news_title"
android:paddingLeft="10dp"
android:layout_marginTop="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/news_date"
android:paddingEnd="10dp"
android:paddingStart="10dp"
android:text="Date"
android:paddingRight="5dp"/>
</RelativeLayout>
<ImageView
android:layout_width="match_parent"
android:adjustViewBounds="true"
android:id="#+id/news_image"
android:src="#drawable/icon_youtube"
android:layout_below="#id/wrapper_news"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/news_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/news_image"
android:fontFamily="#font/roboto"
android:padding="10dp"
android:text="News Description"
android:firstBaselineToTopHeight="0dp"
android:includeFontPadding="false"
android:lineSpacingExtra="2dp"
android:textColor="#color/black"
android:textSize="17sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/wrapper_cardview"
android:padding="10dp"
android:textSize="18sp"
android:text="Similar News"
android:visibility="gone"
android:id="#+id/label_similar_news"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/news_recy"
android:layout_below="#id/label_similar_news"/>
</RelativeLayout>
</androidx.core.widget.NestedScrollView>
</RelativeLayout>
</RelativeLayout>
And finally, I am trying to get the list from here:
CryptoListAdapter
package com.noticripto.adapters;
import android.content.Context;
import android.graphics.Color;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.noticripto.retrofit.Datum;
import com.noticripto.R;
import java.util.List;
public class CryptoListAdapter extends
RecyclerView.Adapter<CryptoListAdapter.ViewHolder> {
private List<Datum> mData;
private ItemClickListener mClickListener;
ImageView arrowImage;
RelativeLayout layout;
RelativeLayout symbolBG;
// data is passed into the constructor
public CryptoListAdapter(List<Datum> data) {
this.mData = data;
}
// Usually involves inflating a layout from XML and returning the holder
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.crypto_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
layout = view.findViewById(R.id.relativeBG);
symbolBG = view.findViewById(R.id.symbolBG);
arrowImage = view.findViewById(R.id.arrow_img);
return viewHolder;
}
// Involves populating data into the item through holder
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Get the data model based on position
Datum datum = mData.get(position);
TextView symbolName = holder.symbolName;
symbolName.setText(" (" + datum.getSymbol() + ")");
// Set item views based on your views and data model
TextView name = holder.name;
name.setText(datum.getName());
TextView symbolNameDetails = holder.symbolNameDetails;
symbolNameDetails.setText(datum.getSymbol());
TextView price = holder.price;
TextView priceDetails = holder.priceDetails;
if(datum.getQuote().getUSD().getPrice() >= 1) {
price.setText("$" + String.format("%.2f", datum.getQuote().getUSD().getPrice()));
priceDetails.setText("$" + String.format("%.2f", datum.getQuote().getUSD().getPrice()));
}else{
price.setText("$" + String.format("%f", datum.getQuote().getUSD().getPrice()));
priceDetails.setText("$" + String.format("%.2f", datum.getQuote().getUSD().getPrice()));
}
//TextView marketCap = holder.marketCap;
//marketCap.setText("Market Cap: $" + String.format("%,d",
Math.round(datum.getQuote().getUSD().getMarketCap())));
//TextView volume24h = holder.volume24h;
//volume24h.setText("Volume/24h: $" + String.format("%,d",
Math.round(datum.getQuote().getUSD().getVolume24h())));
//TextView textView1h = holder.textView1h;
//textView1h.setText(String.format("1h: %.2f",
datum.getQuote().getUSD().getPercentChange1h()) + "%");
TextView textView24h = holder.textView24h;
textView24h.setText(String.format("%.2f", datum.getQuote().getUSD().getPercentChange24h()) + "%");
if(datum.getQuote().getUSD().getPercentChange24h() < 0.0){
//red
textView24h.setText(String.format("%.2f", Math.abs(datum.getQuote().getUSD().getPercentChange24h())) + "%");
textView24h.setTextColor(Color.parseColor("#ffffff"));
arrowImage.setImageResource(R.drawable.arrow_down_white);
layout.setBackgroundColor(Color.parseColor("#EA3943"));
symbolBG.setBackgroundColor(Color.parseColor("#EA3943"));
priceDetails.setTextColor(Color.parseColor("#EA3943"));
}else{
//green
textView24h.setText(String.format("%.2f",
Math.abs(datum.getQuote().getUSD().getPercentChange24h())) + "%");
textView24h.setTextColor(Color.parseColor("#ffffff"));
arrowImage.setImageResource(R.drawable.arrow_up_white);
layout.setBackgroundColor(Color.parseColor("#18C784"));
symbolBG.setBackgroundColor(Color.parseColor("#18C784"));
priceDetails.setTextColor(Color.parseColor("#18C784"));
}
//TextView textView7d = holder.textView7d;
//textView7d.setText(String.format("7d: %.2f",
datum.getQuote().getUSD().getPercentChange7d()) + "%");
}
// Returns the total count of items in the list
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
// Your holder should contain a member variable
// for any view that will be set as you render a row
TextView name;
TextView price;
TextView marketCap;
TextView volume24h;
TextView textView1h;
TextView textView24h;
TextView textView7d;
TextView symbolName;
TextView priceDetails;
TextView symbolNameDetails;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
ViewHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
name = itemView.findViewById(R.id.name);
price = itemView.findViewById(R.id.price);
//marketCap = itemView.findViewById(R.id.marketCap);
// volume24h = itemView.findViewById(R.id.volume24h);
//textView1h = itemView.findViewById(R.id.textView1h);
textView24h = itemView.findViewById(R.id.textView24h);
//textView7d = itemView.findViewById(R.id.textView7d);
symbolName = itemView.findViewById(R.id.symbolName);
priceDetails = itemView.findViewById(R.id.priceDetails);
symbolNameDetails = itemView.findViewById(R.id.symbolNameDetails);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view,
getAdapterPosition());
}
}
// convenience method for getting data at click position
public Datum getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
The log doesn't say anything helpful just that the list might be empty but the same list is working on the MainActivity so, I believe the problem is inside my NewsDetailActivity.
I also tried some of the answers and none of them helped me:
RecyclerView is not showing
RecyclerView is not showing items
CardView is not showing properly in RecyclerView
Again, i just want to display my list from CryptoListAdapter under the NewsDetailActivity toolbar...in a nice cardview
This is what I want to do...
this is simple and normal! you fill your array in getCoinList() but set adapter for RecyclerView in initViews() in this way your array not filled yet but you pass it to your recycler! , you should get your array first , then pass it to adapter and set adapter to RecyclerView.
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.
When a user logs in to my app, they can either click the view students button or daily grading button. The view students will display a student's image and their name. The daily grading will display the student's image, name, and two checkboxes that says pass or fail. Now the issue I have is that the checkboxes for pass and fail are showing up in my activity_view_students.xml view when it should not be. It should only show when a user clicks daily grading. I will put images below to make it clearer
What it looks like in the activity_view_students.xml
What it should look like in activity_view_students.xml
I will paste all relevant code below.
ViewStudents.java
package com.example.studenttracker;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ViewStudents extends AppCompatActivity {
RecyclerView recyclerView;
Button addStudent;
private DatabaseReference myRef;
public ArrayList<Students> students;
private RecyclerAdapter recyclerAdapter;
private Button orderStudents;
private EditText mEditTextAge;
private EditText mEditTextAssignment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_students);
recyclerView = findViewById(R.id.recyclerView);
addStudent = findViewById(R.id.addStudentButton);
mEditTextAge = findViewById(R.id.EditTextAge);
mEditTextAssignment = findViewById(R.id.EditTextAssignment);
orderStudents = findViewById(R.id.orderStudents);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ViewStudents.this, AddStudent.class));
}
});
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setHasFixedSize(true);
myRef = FirebaseDatabase.getInstance().getReference();
students = new ArrayList<>();
ClearAll();
GetDataFromFirebase();
}
private void GetDataFromFirebase() {
Query query = myRef.child("student");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
Students student = new Students();
if (snapshot.child("url").getValue() == null) {
student.setImageUrl(snapshot.child("imageUrl").getValue().toString());
}
else {
student.setImageUrl(snapshot.child("url").getValue().toString());
}
// student.setAge(mEditTextAge.getText().toString());
// student.setAssignment(mEditTextAssignment.getText().toString().trim());
student.setName(snapshot.child("name").getValue().toString());
students.add(student);
}
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), students);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void ClearAll() {
if (students != null) {
students.clear();
if(recyclerAdapter != null) {
recyclerAdapter.notifyDataSetChanged();
}
}
students = new ArrayList<>();
}
public void orderStudents(View view) {
Collections.sort( students, new Comparator<Students>() {
#Override
public int compare( Students o1, Students o2 ) {
return o1.name.compareTo( o2.name );
}
});
recyclerAdapter.notifyDataSetChanged();
}
}
RecyclerAdapter.java
package com.example.studenttracker;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Students> studentsArrayList;
public RecyclerAdapter(Context mContext, ArrayList<Students> studentsArrayList) {
this.mContext = mContext;
this.studentsArrayList = studentsArrayList;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_student_item,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//TextView
holder.textView.setText(studentsArrayList.get(position).getName());
Glide.with(mContext).load(studentsArrayList.get(position).getImageUrl()).into(holder.imageView);
// if (studentsArrayList.get(position).get) { //check if you need the buttons or not
// holder..setVisibility(View.VISIBLE);
// holder.checkBox2.setVisibility(View.VISIBLE);
// } else {
// holder.checkBox.setVisibility(View.GONE);
// holder.checkBox2.setVisibility(View.GONE);
// }
}
#Override
public int getItemCount() {
return studentsArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
}
}
});
}
}
}
activity_view_students.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=".ViewStudents">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="409dp"
android:layout_height="729dp"
android:layout_marginEnd="1dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</androidx.recyclerview.widget.RecyclerView>
<Button
android:id="#+id/addStudentButton"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="Add Students"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/orderStudents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="orderStudents"
android:text="Order Students"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
daily_grading.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=".DailyGrading">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_student_item.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="wrap_content"
tools:context=".DailyGrading">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:foreground="?android:attr/selectableItemBackground"
app:cardElevation="2dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.cardview.widget.CardView>
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="52dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="50dp"
android:paddingTop="20dp"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_margin="10dp"
android:textSize="16sp" />
<CheckBox
android:id="#+id/passc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:text="PASS" />
<CheckBox
android:id="#+id/failc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:layout_toRightOf="#+id/passc"
android:text="FAIL" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
GradingRecyclerAdapter
package com.example.studenttracker;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class GradingRecyclerAdapter extends RecyclerView.Adapter<GradingRecyclerAdapter.ViewHolder> {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Students> studentsArrayList;
public GradingRecyclerAdapter(Context mContext, ArrayList<Students> studentsArrayList) {
this.mContext = mContext;
this.studentsArrayList = studentsArrayList;
}
#NonNull
#Override
public GradingRecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_grading_student_item,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//TextView
holder.textView.setText(studentsArrayList.get(position).getName());
Glide.with(mContext).load(studentsArrayList.get(position).getImageUrl()).into(holder.imageView);
}
#Override
public int getItemCount() {
return studentsArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
Button passButton;
Button failButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
passButton = itemView.findViewById(R.id.PASS);
failButton = itemView.findViewById(R.id.FAIL);
// passButton.setVisibility(View.GONE);
// failButton.setVisibility(View.GONE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
}
}
});
}
}
}
activity_grading_student_item
<?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="wrap_content"
tools:context=".DailyGrading">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:foreground="?android:attr/selectableItemBackground"
app:cardElevation="2dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.cardview.widget.CardView>
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="52dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="50dp"
android:paddingTop="20dp"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_margin="10dp"
android:textSize="16sp" />
<CheckBox
android:id="#+id/PASS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:text="PASS" />
<CheckBox
android:id="#+id/FAIL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textView"
android:layout_toRightOf="#+id/PASS"
android:text="FAIL" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
You can simply use different adapters
create another activity_student_item.xml let's say activity_view_student_item.xml and remove the checkboxes from that one
create another adapter for that recyclerView but change
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_student_item,parent,false);
in the new adapter to
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_view_student_item,parent,false);
and in the ViewStudents activity set the recycler's Adapter to that new adapter
I created a page where it will show the firebase data in a RecyclerView. It work but I decided to put a toolbar at the top of the page to have a back function. After I put the toolbar in my layout file, the RecyclerView is not showing any data anymore. I think that my layout XML file is wrong. Thanks in advance for anyone helping.
Actity file
package com.example.attendanceappvqyfyp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.example.attendanceappvqyfyp.Interface.itemClickListener;
import com.example.attendanceappvqyfyp.Common.Common;
import com.example.attendanceappvqyfyp.Model.LecturerClass;
import com.example.attendanceappvqyfyp.Model.News;
import com.example.attendanceappvqyfyp.Model.Timetable;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.attendanceappvqyfyp.Common.Common;
public class LecturerClassList extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference lecturerclass;
DatabaseReference news;
FirebaseRecyclerAdapter<LecturerClass,LecturerClassViewHolder> adapter;
TextView newscourse, newsclass;
EditText newsdescription;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lecturer_class_list);
//Firebase
database = FirebaseDatabase.getInstance();
lecturerclass = database.getReference("Class");
news = database.getReference("News");
recyclerView = (RecyclerView)findViewById(R.id.recycler_lecturerclass);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Toolbar code
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Class List");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
loadLecturerClass(Common.currentLecturer.getName());
}
private void loadLecturerClass(String Lecturer) {
adapter = new FirebaseRecyclerAdapter<LecturerClass, LecturerClassViewHolder>(LecturerClass.class, R.layout.lecturerclass_item, LecturerClassViewHolder.class, lecturerclass.orderByChild("lecturer").equalTo(Lecturer)) {
#Override
protected void populateViewHolder(LecturerClassViewHolder lecturerClassViewHolder, LecturerClass lecturerClass, int i) {
lecturerClassViewHolder.lclasstitle.setText("Class :" + adapter.getRef(i).getKey());
lecturerClassViewHolder.ldate.setText("Day :" + lecturerClass.getDay());
lecturerClassViewHolder.ltime.setText("Time :" + lecturerClass.getTime());
lecturerClassViewHolder.lclassroom.setText("Classroom :" + lecturerClass.getClassroom());
lecturerClassViewHolder.lcourse.setText(lecturerClass.getCourse());
lecturerClassViewHolder.setItemClickListener(new itemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
//code later
}
});
}
};
recyclerView.setAdapter(adapter);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle().equals(Common.News))
{
showNewsDialog(adapter.getRef(item.getOrder()).getKey(),adapter.getItem(item.getOrder()));
}
return super.onContextItemSelected(item);
}
private void showNewsDialog(final String course, final LecturerClass item) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(LecturerClassList.this);
alertDialog.setTitle("Make Announcement");
alertDialog.setMessage("Make announcement about this class.");
LayoutInflater inflater = this.getLayoutInflater();
View lecturer_make_news = inflater.inflate(R.layout.activity_lecturer_make_news, null);
newscourse = lecturer_make_news.findViewById(R.id.NewsCourse);
newsclass = lecturer_make_news.findViewById(R.id.NewsClass);
newsdescription = lecturer_make_news.findViewById(R.id.NewsDescription);
newscourse.setText("Course: "+item.getCourse());
newsclass.setText("Subject: " + course);
alertDialog.setView(lecturer_make_news);
alertDialog.setPositiveButton("Post", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if(newsdescription.getText().toString().isEmpty()){
Toast.makeText(LecturerClassList.this, "Post cancel, description cannot be empty.", Toast.LENGTH_SHORT).show();
}
else {
News lnews = new News(
item.getCourse(),
course,
newsdescription.getText().toString()
);
news.child(String.valueOf(System.currentTimeMillis())).setValue(lnews);
Toast.makeText(LecturerClassList.this, "Announcement post successfully.", Toast.LENGTH_SHORT).show();
finish();
}
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();;
}
});
alertDialog.show();
}
}
Activity file for viewholder
package com.example.attendanceappvqyfyp;
import android.view.ContextMenu;
import android.view.View;
import android.widget.TextView;
import com.example.attendanceappvqyfyp.Common.Common;
import androidx.recyclerview.widget.RecyclerView;
import com.example.attendanceappvqyfyp.Interface.itemClickListener;
public class LecturerClassViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnCreateContextMenuListener {
public TextView lclasstitle, ldate, ltime, lclassroom, lcourse;
private itemClickListener itemClickListener;
public LecturerClassViewHolder(View itemView) {
super(itemView);
lclasstitle = (TextView)itemView.findViewById(R.id.lclasstitle);
ldate = (TextView)itemView.findViewById(R.id.ldate);
ltime = (TextView)itemView.findViewById(R.id.ltime);
lclassroom = (TextView)itemView.findViewById(R.id.lclassroom);
lcourse = (TextView)itemView.findViewById(R.id.lcourse);
itemView.setOnCreateContextMenuListener(this);
itemView.setOnClickListener(this);
}
public void setItemClickListener(itemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view, getAdapterPosition(), false);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select");
menu.add(0,0,getAdapterPosition(), Common.News);
}
}
Layout file for recyclerview
<?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=".LecturerClassList">
<android.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:theme="#style/ThemeOverlay.AppCompat.Dark" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_lecturerclass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constraintTop_toBottomOf="#+id/toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>
Layout file for itemview
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="160dp"
app:cardElevation="4dp"
android:layout_marginBottom="8dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/lclasstitle"
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/ldate"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignBottom="#id/lclasstitle"
android:layout_marginBottom="-40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/ltime"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignBottom="#id/ldate"
android:layout_marginBottom="-40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/lclassroom"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/lcourse"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:text=""
android:visibility="invisible"
android:textColor="#android:color/black"
android:textSize="20sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
Thanks to ZeePee for giving this link Display Back Arrow on Toolbar, although the toolbar didnt work for me, i change it back to actionbar and use the code from the link and it work.
Try adding horizontal constraints for Toolbar and Recycler View. After that you need to specify where do you want your single item widgets in Relative layout
I have made an android application, and its getting successfully compiled without any errors. But when I run app in my android phone, then it does not show the desired output.
This is my MainActivity.java:
package wahab.com.timetabledemo;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUIViews();
initToolbar();
}
private void setupUIViews(){
toolbar = (Toolbar)findViewById(R.id.ToolbarMain);
listView = (ListView)findViewById(R.id.lvMain);
}
private void initToolbar(){
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("TimeTable App");
}
private void setupListView(){
String[] title = getResources().getStringArray(R.array.Main);
String[] description = getResources().getStringArray(R.array.Description);
SimpleAdaptor simpleAdaptor = new SimpleAdaptor(this, title, description);
listView.setAdapter(simpleAdaptor);
}
public class SimpleAdaptor extends BaseAdapter{
private Context mContext;
private LayoutInflater layoutInflater;
private TextView title, description;
private String[] titleArray;
private String[] descriptionArray;
private ImageView imageView;
public SimpleAdaptor(Context context, String[] title, String[] description){
mContext = context;
titleArray = title;
descriptionArray = description;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return titleArray.length;
}
#Override
public Object getItem(int i) {
return titleArray[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null){
view = layoutInflater.inflate(R.layout.main_activity_single_item,null);
}
title = (TextView)view.findViewById(R.id.tvMain);
description = (TextView)view.findViewById(R.id.tvDescription);
imageView = (ImageView)view.findViewById((R.id.ivMain));
title.setText(titleArray[i]);
description.setText(descriptionArray[i]);
if(titleArray[i].equalsIgnoreCase("Timetable")){
imageView.setImageResource(R.drawable.timetable);
}
else if(titleArray[i].equalsIgnoreCase("Subjects")){
imageView.setImageResource(R.drawable.book);
}
else if(titleArray[i].equalsIgnoreCase("Faculty")){
imageView.setImageResource(R.drawable.contact);
}
else{
imageView.setImageResource(R.drawable.settings);
}
return view;
}
}
}
The given above is a error free code.
This is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="wahab.com.timetabledemo.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/ToolbarMain"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="#color/colorPrimary"
app:titleTextColor="#color/white">
</android.support.v7.widget.Toolbar>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lvMain"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:dividerHeight="10dp"
android:layout_below="#+id/ToolbarMain"
android:divider="#null">
</ListView>
</RelativeLayout>
In my activity_main.xml, I have used a RelativeLayout in which I have defined a Toolbar and a ListView. A ListView is defined so that I can add different list of operation.
This is my main_activity_single_item.xml:
<android.support.v7.widget.CardView android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/colorAccent"
android:elevation="4dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="80dp"
android:layout_height="105dp"
android:id="#+id/ivMain"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvMain"
android:textStyle="bold"
android:text="Timetable"
android:layout_marginTop="6dp"
android:layout_marginLeft="6dp"
android:layout_toRightOf="#+id/ivMain"
android:textSize="25sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvDescription"
android:text="description"
android:layout_marginLeft="6dp"
android:layout_marginTop="3dp"
android:layout_below="#+id/tvMain"
android:layout_toRightOf="#+id/ivMain"
android:textSize="16sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvClick"
android:textSize="12sp"
android:text="click to know more"
android:layout_marginTop="6dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/tvDescription"
android:layout_alignBottom="#+id/ivMain"/>
</RelativeLayout>
In this above xml file, I have created a CardView which will consist of an ImageView and 3 TextView, which is placed using a RelativeLayout.
So, my code is getting compiled properly and my app is also running but am not getting the desired output.
You need to call setupListView() in onCreate to display the list
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUIViews();
initToolbar();
setupListView(); // to display list
^^^^^^^^^^
}