Clickable element of ListView with gridView inside (Android) - java

I want to make listView element clickable.
When i add gridView inside listView then i cant click on listView element..
How to make listView element clickable when gridView is inside listView?
I try to set focusable, descendantFocusability, clickable...
ProductsFragment.java
package pl.pieczolap.ui.products;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
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 com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import pl.globoox.pieczolap.R;
import pl.pieczolap.API.getProducts;
import pl.pieczolap.MyGridView;
public class ProductsFragment extends Fragment {
private ProductsViewModel StampViewModel;
ArrayList<String> product_uid_shop = new ArrayList();
ArrayList<String> product_uid_product = new ArrayList();
ArrayList<String> product_name = new ArrayList();
ArrayList<String> product_info = new ArrayList();
ArrayList<String> product_stamps = new ArrayList();
ArrayList<String> product_clientStamps = new ArrayList();
MyGridView gridView_stamps;
ListView listView_products;
SharedPreferences sharedPref;
Integer clientStamps;
Integer needStamps;
ImageView imageView_loadingData;
TextView textView_winner;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
StampViewModel =
ViewModelProviders.of(this).get(ProductsViewModel.class);
View root = inflater.inflate(R.layout.fragment_products, container, false);
// LOAD GIF LOADING IMAGE
imageView_loadingData = root.findViewById(R.id.imageView_loadingData);
Glide.with(root).load(R.drawable.loadingdots).placeholder(R.drawable.loadingdots).into(imageView_loadingData);
listView_products = root.findViewById(R.id.listView_products);
sharedPref = getActivity().getApplicationContext().getSharedPreferences("pl.piecozlap", Context.MODE_PRIVATE);
Bundle arguments = this.getArguments();
String uid_shop = arguments.getString("uid_shop", "none");
// GET ALL STAMPS
Response.Listener<String> responseListenerUserComments = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
int errorCode = jsonResponse.getInt("errorCode");
// CANT CONNECT TO DATABASE
if (errorCode == 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
builder.setMessage("Brak połączenia z bazą danych!").setNegativeButton("PONÓW", null).create().show();
}
// GET STAMP AND PRODUCT INFO
if (errorCode == 2) {
JSONArray products = jsonResponse.getJSONArray("products");
for (int i = 0; i < products.length(); i++) {
JSONObject jsonObject = products.getJSONObject(i);
product_uid_shop.add(jsonObject.getString("uid_shop"));
product_uid_product.add(jsonObject.getString("uid_product"));
product_name.add(jsonObject.getString("name"));
product_info.add(jsonObject.getString("info"));
product_stamps.add(jsonObject.getString("stamps"));
product_clientStamps.add(jsonObject.getString("clientStamps"));
}
// HIDE LOADING GIF
imageView_loadingData.setVisibility(View.INVISIBLE);
ProductsAdapter productsAdapter = new ProductsAdapter();
listView_products.setAdapter(productsAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
getProducts getStamps = new getProducts(sharedPref.getString("uid_client", "none"), uid_shop, responseListenerUserComments);
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(getStamps);
return root;
}
// LISTVIEW CUSTOMADAPTER
// LISTVIEW CUSTOMADAPTER
// LISTVIEW CUSTOMADAPTER
// LISTVIEW CUSTOMADAPTER
public class ProductsAdapter extends BaseAdapter {
#Override
public int getCount() {
return product_uid_shop.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_products, null);
clientStamps = Integer.valueOf(product_clientStamps.get(position));
needStamps = Integer.valueOf(product_stamps.get(position));
TextView textView_product_name = convertView.findViewById(R.id.textView_product_name);
TextView textView_product_info = convertView.findViewById(R.id.textView_product_info);
textView_product_name.setText(String.valueOf(clientStamps));
textView_product_info.setText(product_info.get(position));
// WINNER TEXTVIEW
TextView textView_winner = convertView.findViewById(R.id.textView_winner);
if (clientStamps == needStamps) {
textView_winner.setVisibility(View.VISIBLE);
} else {
textView_winner.setVisibility(View.INVISIBLE);
}
// -------------------- //
// CLICK ON SHOP //
// -------------------- //
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAGA", "sasdadsa");
new AlertDialog.Builder(getActivity().getApplicationContext())
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Continue with delete operation
}
})
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
gridView_stamps = convertView.findViewById(R.id.gridView_stamps);
StampsAdapter stampAdapter = new StampsAdapter();
gridView_stamps.setAdapter(stampAdapter);
gridView_stamps.setClickable(false);
return convertView;
}
}
// STAMP GRIDVIEW
// STAMP GRIDVIEW
// STAMP GRIDVIEW
// STAMP GRIDVIEW
public class StampsAdapter extends BaseAdapter {
#Override
public int getCount() {
return needStamps;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_onestamp, null);
if (position < clientStamps) {
final ImageView imageView = convertView.findViewById(R.id.imgageView_onestamp);
Picasso.get().load("http://pieczolap.pl/admin/shops/999/stamp.jpg").into(imageView);
}
return convertView;
}
}
}
customlayout_products.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="wrap_content"
android:layout_height="400dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="50dp"
android:background="#drawable/customlayout_shops_background"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:background="#drawable/customlayout_shops_background">
<TextView
android:id="#+id/textView_product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Info"
android:textSize="15dp" />
<TextView
android:id="#+id/textView_product_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView_product_name"
android:layout_margin="5dp"
android:text="Info"
android:textSize="10dp" />
</RelativeLayout>
<pl.pieczolap.MyGridView
android:id="#+id/gridView_stamps"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:columnWidth="100dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="4"
android:padding="10dp"
android:stretchMode="spacingWidth"
android:verticalSpacing="10dp"
app:layout_constraintTop_toBottomOf="#id/relativeLayout"
tools:ignore="MissingConstraints" />
<TextView
android:id="#+id/textView_winner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:gravity="center"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:rotation="-6"
android:layout_margin="5dp"
android:textColor="#FF0000"
android:textStyle="bold"
android:text="Zebrano wszystkie!"
android:textSize="30dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_products.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"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:focusable="true"
android:layout_height="match_parent">
<ListView
android:id="#+id/listView_products"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:divider="#null"
android:focusable="true"
android:clickable="true"
android:dividerHeight="10dp"
android:padding="4dp"
android:layout_marginBottom="70dp"
app:layout_constraintTop_toBottomOf="#+id/button_addShop" />
<ImageView
android:id="#+id/imageView_loadingData"
android:layout_width="350dp"
android:layout_height="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Related

RecyclerView is not showing in Activity

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.

how to display recyclerview in a fragment after fetching an api on the click of a button

I am trying to display some recipe data after you search the recipe in the search bar and click the search button inside the search fragment. I am using recycler view inside the search fragment to display the data below the search bar and the button.
Here is the code for the fragment_search.xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.SearchFragment">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="-230dp"
android:src="#drawable/home_oval" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FOODIES"
android:textSize="40dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<SearchView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:queryHint="Find your today's recipe"
android:iconifiedByDefault="false"
android:background="#drawable/searchoval"
android:id="#+id/searchbar"
/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="search"
android:background="#drawable/rounded_btn"
android:layout_below="#+id/searchbar"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="#+id/button1"/>
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:src="#drawable/ic_man_searching_location_using_gps_2127154_0"
android:layout_below="#+id/button1"
android:id="#+id/searching_logo"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searching_text"
android:text="Search for yummy delicacies today"
android:layout_centerHorizontal="true"
android:textAlignment="center"
android:fontFamily="#font/quicksand"
android:layout_below="#+id/searching_logo"
android:textSize="25dp"
android:textColor="#color/black"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button1"
android:id="#+id/recycler_view"
>
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</FrameLayout>
Here is my SearchFragment.java file.
package com.example.recipeappandroid.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.recipeappandroid.Adapter.RecipeAdapter;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
Button click;
//public static TextView fetchedText;
ImageView searching_logo;
TextView searching_text;
SearchView searchbar;
String query="";
RecyclerView recyclerView;
public static ArrayList<Recipe> recipeList;
public static RecipeAdapter recipeAdapter;
private RequestQueue mRequestQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
click = (Button) view.findViewById(R.id.button1);
//fetchedText = (TextView) view.findViewById(R.id.fetcheddata);
searchbar = (SearchView) view.findViewById(R.id.searchbar);
searching_logo = view.findViewById(R.id.searching_logo);
searching_text = view.findViewById(R.id.searching_text);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
//recipeAdapter = new RecipeAdapter();
recyclerView.setAdapter(recipeAdapter);
recipeList = new ArrayList<>();
//getData();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query = searchbar.getQuery().toString();
String url = "http://localhost:5000/" + query;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
JSONObject recipes = jsonObject.getJSONObject("recipe");
//Recipe recipe = new Recipe();
String recipe_img = recipes.getString("image");
String recipe_title = recipes.getString("label");
String recipe_data = recipes.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
}
recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(SearchFragment.this,"Error Occured",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
mRequestQueue = Volley.newRequestQueue(getContext());
mRequestQueue.add(jsonArrayRequest);
/* Log.d("QUEEEERRRYYYY",query);
ApiCall process = new ApiCall(searching_logo,searching_text);
process.execute(query);*/
}
});
return view;
}
}
I am fething the api and setting the arraylists and adapter inside the onClick listener
but I keep getting the "E/RecyclerView: No adapter attached; skipping layout" Error in the logcat.
Here is the code for the adapter.
package com.example.recipeappandroid.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import com.example.recipeappandroid.Viewholder.recipeViewHolder;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecipeAdapter extends RecyclerView.Adapter<recipeViewHolder>{
private Context mContext;
private ArrayList<Recipe> mRecipe;
public RecipeAdapter(Context context,ArrayList<Recipe> recipe) {
mContext = context;
mRecipe = recipe;
}
public void setData(ArrayList<Recipe> mRecipe) {
this.mRecipe = mRecipe;
}
#NonNull
#Override
public recipeViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_row, viewGroup, false);
return new recipeViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull recipeViewHolder viewHolder, int i) {
Recipe recipe = mRecipe.get(i);
Picasso.get().load(recipe.getImg()).into(viewHolder.image);
viewHolder.recipe_title.setText(recipe.getTitle());
viewHolder.recipe_data.setText(recipe.getData());
}
#Override
public int getItemCount() {
return mRecipe.size();
}
}
Here is my solution
//recipeAdapter = new RecipeAdapter();
recyclerView.setAdapter(recipeAdapter);
recipeList = new ArrayList<>();
//change code:
recipeList = new ArrayList<>();
recipeAdapter = new RecipeAdapter(getContext(), recipeList);
recyclerView.setAdapter(recipeAdapter);
//after get data in API:
//recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();

Showing xml for correct view

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

Android ListView not scrolling at all

I've a ListView that gets populated from a JSON response.
The results go beyond the screen and whatever I tried the listview won't be scrolling.
Currently the XML looks like the following:
<?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"
tools:context=".DrinkActivity">
<ListView
android:id="#+id/drinkList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:scrollbarSize="3dp"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="vertical"
android:scrollingCache="true"
android:smoothScrollbar="true" />
</LinearLayout>
Adapter which the listview is using:
package com.example.tijn.bartenderapp;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Map;
public class DrinksAdapter extends ArrayAdapter<Drink> {
private Activity activity;
private ArrayList<Drink> drinksArrayList;
private static LayoutInflater inflater = null;
public DrinksAdapter(Activity activity, int textViewResourceId, ArrayList<Drink> _drinksArrayList) {
super(activity, textViewResourceId, _drinksArrayList);
try {
this.activity = activity;
this.drinksArrayList = _drinksArrayList;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception ex) {
}
}
#Override
public int getCount() {
return drinksArrayList.size();
}
public Drink getItem(Drink position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView display_name;
public TextView ingredient0;
public TextView ingredient1;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final DrinksAdapter.ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.drinksrow, null);
holder = new DrinksAdapter.ViewHolder();
holder.ingredient0 = (TextView) vi.findViewById(R.id.ingredientName0);
holder.ingredient1 = (TextView) vi.findViewById(R.id.ingredientName1);
vi.setTag(holder);
} else {
holder = (DrinksAdapter.ViewHolder) vi.getTag();
}
Drink d = drinksArrayList.get(position);
holder.ingredient0.setText(d.getName());
StringBuilder ingredients = new StringBuilder();
for (Map.Entry<String, Integer> ingredient : d.getIngredients().entrySet()) {
ingredients.append(" ");
ingredients.append(ingredient.getKey());
ingredients.append(", ");
ingredients.append(Integer.toString(ingredient.getValue()));
ingredients.append("ML \n");
}
holder.ingredient1.setText(ingredients.toString().trim());
} catch (Exception e) {
}
return vi;
}
}
Here is the contents of the drinksrow.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/ingredientName0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginTop="40dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ingredientName1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="92dp"
android:layout_marginTop="40dp"
app:layout_constraintStart_toEndOf="#+id/ingredientName0"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ingredientName2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="40dp"
tools:layout_editor_absoluteY="69dp" />
<TextView
android:id="#+id/ingredientName3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="116dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="192dp" />
</android.support.constraint.ConstraintLayout>
Here is the method that sets the ListView :
#Override
public void processFinish(Object output) {
String jsonString = output.toString();
Gson gson = new Gson();
ArrayList<Drink> drinks = gson.fromJson(jsonString, new TypeToken<List<Drink>>(){}.getType());
final ListView listview = (ListView) findViewById(R.id.drinkList);
final DrinksAdapter adapter = new DrinksAdapter(this, R.layout.drinksrow, drinks);
listview.setAdapter(adapter);
listview.setEnabled(false);
}
Already tried to surround the LinearLayout with a ScrollView.
Anybody got an idea?
listview.setEnabled(false);
This disables scrolling.
Not sure why you want to set it to false.
You can use
<ScrollView
android:layout_width="..."
android:layout_height="...">
<LinearLayout
android:orientation="vertical"
android:layout_width="..."
android:layout_height="...">
I use it, and works.

Android - Expandable list view - child data

I have small application written in android. I have tried to implement ExpandableListView into my main layout, but child data do not exists. Collapse works fine but, no data provided.
I have run debugger and see that my list have data.
Here is my code:
main layout - activity_post_details.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_post_details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="hedza.com.durmitortourism.PostDetailsActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center"
android:id="#+id/postDetailsTitleText"
android:textSize="32dp"
android:textStyle="bold"
android:textAlignment="center" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:textSize="16dp"
android:layout_marginTop="18dp"
android:id="#+id/postDescText" />
<ExpandableListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:id="#+id/ExplistDetails"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/postGalleryBtn"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_marginTop="20dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/postLocationBtn"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="20dp"
/>
</RelativeLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
group_item - expandable_list_group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/listTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textColor="#android:color/black"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
</LinearLayout>
expandable_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/expandedListItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
android:paddingTop="10dp"
android:textColor="#000000"
android:textSize="16dp"
android:paddingBottom="10dp" />
</LinearLayout>
ExpandableListAdapter.class
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> expandableListTitle;
private HashMap<String, List<String>> expandableListDetail;
public ExpandableListAdapter(Context context, List<String> expandableListTitle,
HashMap<String, List<String>> expandableListDetail)
{
this.context = context;
this.expandableListTitle = expandableListTitle;
this.expandableListDetail = expandableListDetail;
}
#Override
public Object getChild(int listPosition, int expandedListPosition)
{
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.get(expandedListPosition);
}
#Override
public long getChildId(int listPosition, int expandedListPosition) {
return expandedListPosition;
}
#Override
public View getChildView(int listPosition, final int expandedListPosition,
boolean isLastChild, View convertView, ViewGroup parent)
{
final String expandedListText = (String) getChild(listPosition, expandedListPosition);
if (convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.expandable_list_item, null);
}
TextView expandedListTextView = (TextView) convertView
.findViewById(R.id.expandedListItem);
expandedListTextView.setText(expandedListText);
return convertView;
}
#Override
public int getChildrenCount(int listPosition) {
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.size();
}
#Override
public Object getGroup(int listPosition) {
return this.expandableListTitle.get(listPosition);
}
#Override
public int getGroupCount() {
return this.expandableListTitle.size();
}
#Override
public long getGroupId(int listPosition) {
return listPosition;
}
#Override
public View getGroupView(int listPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
String listTitle = (String) getGroup(listPosition);
if (convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.expandable_list_group, null);
}
TextView listTitleTextView = (TextView) convertView
.findViewById(R.id.listTitle);
listTitleTextView.setTypeface(null, Typeface.BOLD);
listTitleTextView.setText(listTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int listPosition, int expandedListPosition) {
return true;
}
}
PostDetailsActivity.class
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class PostDetailsActivity extends AppCompatActivity {
SharedPreferences languageSharedPreferences;
private TextView postTitleTextView;
private TextView postDescTextView;
private ExpandableListView expandableListView;
private ExpandableListAdapter expandableListAdapter;
private List<String> detailsList;
private HashMap<String, List<String>> expandableListDetail;
private Button galleryBtn;
private Button locationBtn;
String locationJSON = null;
String title = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_details);
// setting icon in the action bar
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
// get postID from post activity bundle
Intent intent = getIntent();
String postID = intent.getStringExtra("postID");
// getting language from shared preferences
languageSharedPreferences = getSharedPreferences("LanguagePreferences",
Context.MODE_PRIVATE);
String language = languageSharedPreferences.getString("lang", "me");
final ArrayList<String> viewPagerImages = new ArrayList<>();
// expandable list details initialization
detailsList = new ArrayList<String>();
expandableListDetail = new HashMap<String, List<String>>();
// initialize elements
postTitleTextView = (TextView) findViewById(R.id.postDetailsTitleText);
postDescTextView = (TextView) findViewById(R.id.postDescText);
expandableListView = (ExpandableListView) findViewById(R.id.ExplistDetails);
galleryBtn = (Button) findViewById(R.id.postGalleryBtn);
locationBtn = (Button) findViewById(R.id.postLocationBtn);
// get data from DB by post id
final PostSQLiteManager postObject = new PostSQLiteManager(getApplicationContext());
postObject.openConnection();
JSONObject posts = postObject.getPostsById(postID);
postObject.close();
try
{
JSONArray array = posts.getJSONArray("DATA");
JSONObject arrayObject = array.getJSONObject(0);
String[] images = arrayObject.getString("IMAGES").split(",");
for(int i = 0; i < images.length; i++){
viewPagerImages.add(images[i]);
}
title = arrayObject.getString("TITLE");
// set properties values
postTitleTextView.setText(arrayObject.getString("TITLE"));
postDescTextView.setText(arrayObject.getString("DESC"));
String postWebsite = arrayObject.getString("WEBSITE");
String postEmail = arrayObject.getString("EMAIL");
String postTelephone = arrayObject.getString("TELEPHONE");
locationJSON = arrayObject.getString("LOCATION");
// handling languages
if(language.contentEquals("me"))
{
detailsList.add("Web Stranica: "+postWebsite);
detailsList.add("Telefon: "+postTelephone);
detailsList.add("E-pošta: "+postEmail);
expandableListDetail.put("Detalji", detailsList);
galleryBtn.setText(R.string.galleryPostME);
locationBtn.setText(R.string.locationPostME);
}
else
{
detailsList.add("Website: "+postWebsite);
detailsList.add("Telephone: "+postTelephone);
detailsList.add("E-mail: "+postEmail);
expandableListDetail.put("Details", detailsList);
galleryBtn.setText(R.string.galleryPostEN);
locationBtn.setText(R.string.locationPostEN);
}
final List<String> listTitles = new ArrayList<>(expandableListDetail.keySet());
// generate list
expandableListAdapter = new ExpandableListAdapter(this, listTitles,
expandableListDetail);
expandableListView.setAdapter(expandableListAdapter);
// click on gallery button
galleryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!viewPagerImages.isEmpty()){
Intent galleryIntent = new Intent(getApplicationContext(), GalleryActivity.class);
galleryIntent.putStringArrayListExtra("images", viewPagerImages);
startActivity(galleryIntent);
}else{
Toast.makeText(getApplicationContext(), "Nema slika", Toast.LENGTH_SHORT)
.show();
}
}
});
// click on location button
locationBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent locationIntent = new Intent(getApplicationContext(), MapActivity.class);
locationIntent.putExtra("location", locationJSON);
locationIntent.putExtra("title", title);
startActivity(locationIntent);
}
});
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listTitles.get(groupPosition) + " List Expanded.",
Toast.LENGTH_SHORT).show();
}
});
}
catch(JSONException exception) {
exception.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
super.onCreateOptionsMenu(menu);
languageSharedPreferences = getSharedPreferences("LanguagePreferences",
Context.MODE_PRIVATE);
String language = languageSharedPreferences.getString("lang", "me");
// generate menu and its items
MenuInflater myMenu = getMenuInflater();
myMenu.inflate(R.menu.menu_layout, menu);
// change menu items depending on selected language
switch(language)
{
case "me":
menu.findItem(R.id.languageID).setTitle(R.string.languageME);
menu.findItem(R.id.aboutID).setTitle(R.string.aboutME);
menu.findItem(R.id.sponsorID).setTitle(R.string.sponsorME);
break;
case "en":
menu.findItem(R.id.languageID).setTitle(R.string.languageEN);
menu.findItem(R.id.aboutID).setTitle(R.string.aboutEN);
menu.findItem(R.id.sponsorID).setTitle(R.string.sponsorEN);
break;
default:
menu.findItem(R.id.languageID).setTitle(R.string.languageME);
menu.findItem(R.id.aboutID).setTitle(R.string.aboutME);
menu.findItem(R.id.sponsorID).setTitle(R.string.sponsorME);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.languageID:
Intent languageIntent = new Intent(getApplicationContext(), LanguageActivity.class);
startActivity(languageIntent);
return true;
case R.id.aboutID:
Intent aboutIntent = new Intent(getApplicationContext(), AboutActivity.class);
startActivity(aboutIntent);
return true;
case R.id.sponsorID:
Intent sponsorIntent = new Intent(getApplicationContext(), SponsorActivity.class);
startActivity(sponsorIntent);
default:
return true;
}
}
}
Does anyone have an idea what's wrong here?
Thank you in advance.

Categories