Unable to populate any Cards in RecyclerView, possible cause? - java

I am trying to populate CardView's inside a RecyclerView. Though I am able to log all the adapter values(to make sure they are non-empty) I can't populate any in the UI. Here is the Activity Code:
FoodActivity.class
public class FoodActivity extends AppCompatActivity
{
private RecyclerView foodView;
private List<Result> adapter_data;
private CustomPlacesAdapter adapter;
private LinearLayoutManager llm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
foodView = (RecyclerView)findViewById(R.id.foodRView);
adapter = new CustomPlacesAdapter(adapter_data);
adapter_data = new ArrayList<>();
llm = new LinearLayoutManager(this);
foodView.setLayoutManager(llm);
foodView.setAdapter(adapter);
doGetRequest("restaurants in los angeles airport");
}
private void doGetRequest(final String message)
{
ApiInterfacePlaces apiService =
ApiClientPlaces.getClient().create(ApiInterfacePlaces.class);
Call<PlacesPojo> call = apiService.getValues(message, Util.getKeyForPlaces());
call.enqueue(new Callback<PlacesPojo>()
{
#Override
public void onResponse(Call<PlacesPojo>call, Response<PlacesPojo> response)
{
try
{
Log.e("TAG",""+response.body().toString());
List<Result> response_res = response.body().getResults();
adapter_data = response_res;
adapter.notifyDataSetChanged();
}
catch (Exception e)
{
Toast.makeText(FoodActivity.this, "Check data connection", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<PlacesPojo> call, Throwable t) {
// Log error here since request failed
Log.e("FAILURE", t.toString());
}
});
}
}
Here is the code to the RecyclerView's adapter:
CustomPlacesAdapter.class
public class CustomPlacesAdapter extends RecyclerView.Adapter<CustomPlacesAdapter.HotelsViewHolder>
{
private DataHolder d2 = new DataHolder();
public class HotelsViewHolder extends RecyclerView.ViewHolder
{
private TextView hotelName;
private Typeface face;
private ImageView hotel_logo;
private Context mcontext;
HotelsViewHolder(View itemView)
{
super(itemView);
mcontext = itemView.getContext();
hotelName = (TextView)itemView.findViewById(R.id.hotelName);
face = Typeface.createFromAsset(itemView.getContext().getAssets(), "Fonts/Roboto-Regular.ttf");
hotelName.setTypeface(face);
hotel_logo = (ImageView)itemView.findViewById(R.id.logoOfHotel);
}
}
private static class DataHolder
{
List<Result> feeds;
}
public CustomPlacesAdapter(List<Result> feeds)
{
this.d2.feeds = feeds;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public HotelsViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.food_item, viewGroup, false);
HotelsViewHolder pvh = new HotelsViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(HotelsViewHolder feedViewHolder, int i)
{
feedViewHolder.hotelName.setText(d2.feeds.get(i).getName());
Picasso.with(feedViewHolder.mcontext).load(d2.feeds.get(i).getIcon()).into(feedViewHolder.hotel_logo);
}
#Override
public int getItemCount()
{
if(d2.feeds!=null)
{
return d2.feeds.size();
}
else
{
return 0;
}
}
}
This is the CardView that I use:
food_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_centerHorizontal="true"
app:cardCornerRadius="5dp"
android:layout_height="100dp"
card_view:cardUseCompatPadding="false"
android:id="#+id/cv">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/logoOfHotel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/hotelName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Cross checked many things, still unable to fix the issue, what is possibly causing this? Any help would be much appreciated.

Related

RecyclerView in Android Studio shows some empty lists along with the required lists. The recycler view should display all available audio in the phone

I am trying to make a musicplayer project in Android Studio. I used RecyclerView to display all the audio files present in the phone with a music icon along with the song's name as an item. The problem is the output on certain devices change in the sense that the recycler view shows empty lists with only the music icon on the screen(that are not playable) and upon scrolling, the audio files present in the phone are displayed in the successive lists with the empty lists still at the top. Why are the empty lists displayed and that too only on some devices?
MainActivity.java
public class MainActivity extends AppCompatActivity implements SongsAdapter.SongsViewHolder.OnSongListener {
List<Songs> songs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Dexter.withContext(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
songs= Songs.getSongs(getApplicationContext());
RecyclerView recyclerView = findViewById(R.id.recyclerView);
SongsAdapter songsAdapter = new SongsAdapter(songs,MainActivity.this,MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(songsAdapter);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
})
.check();
}
#Override
public void onSongClick(int position) {
Songs currentSong = songs.get(position);
Intent intent = new Intent(MainActivity.this,PlaySongsActivity.class);
intent.putExtra("SongName",currentSong.getSongName());
intent.putExtra("Uri",currentSong.getUri());
MainActivity.this.startActivity(intent);
}
}
Custom Adapter for recycler view - SongsAdapter.java
public class SongsAdapter extends RecyclerView.Adapter<SongsAdapter.SongsViewHolder>{
private final List<Songs> allSongs;
private SongsViewHolder.OnSongListener mOnSongListener;
Context context;
public SongsAdapter(List<Songs> allSongs, Context context, SongsViewHolder.OnSongListener songListener)
{
this.allSongs = allSongs;
this.context = context;
this.mOnSongListener = songListener;
}
#NonNull
#Override
public SongsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View listItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.songs_list,parent,false);
return new SongsViewHolder(listItem,mOnSongListener);
}
#Override
public void onBindViewHolder(#NonNull SongsViewHolder holder, int position) {
final Songs currentSong = allSongs.get(position);
holder.audio_image.setImageResource(R.drawable.music_icon);
holder.songName.setText(currentSong.getSongName());
}
#Override
public int getItemCount() {
return allSongs.size();
}
public static class SongsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView songName;
public ImageView audio_image;
OnSongListener onSongListener;
public SongsViewHolder(#NonNull View itemView, OnSongListener onSongListener) {
super(itemView);
this.audio_image = itemView.findViewById(R.id.audio_image);
this.songName = itemView.findViewById(R.id.song_name);
this.onSongListener = onSongListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onSongListener.onSongClick(getAdapterPosition());
}
public interface OnSongListener
{
void onSongClick(int position);
}
}
}
To retrieve the audios present in the phone - Songs.java
public class Songs {
private final Uri uri;
private final String songName;
public Songs(Uri uri, String songName) {
this.uri = uri;
this.songName = songName;
}
//Method to get all the audio files from the device
#RequiresApi(api = Build.VERSION_CODES.Q)
public static List<Songs> getSongs(Context context) {
List<Songs> songsList = new ArrayList<Songs>();
ContentResolver contentResolver = context.getContentResolver();
Uri externalContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
};
String sortOrder = MediaStore.Video.Media.TITLE + " ASC";
Cursor cursor = contentResolver.query(
externalContentUri, // Uri
projection, // Projection
null, // Selection
null, // Selection args
sortOrder // Sor order
);
if(!cursor.moveToFirst()) //No music files are present
{
//Create an alertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title);
builder.setCancelable(false);
builder.setPositiveButton("OK", (dialog, which) -> android.os.Process.killProcess(android.os.Process.myPid()));
AlertDialog alert = builder.create();
alert.show();
}
else
{
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
while(cursor.moveToNext())
{
long id = cursor.getLong(idColumn);
String song_name = cursor.getString(nameColumn);
Uri contentUri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
songsList.add(new Songs(contentUri, song_name));
}
}
return songsList;
}
public String getSongName() { return this.songName; }
public Uri getUri() {
return this.uri;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#color/light_azure"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
List Items Layout - songs_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:id="#+id/items_layout"
android:padding="16dp">
<ImageView
android:id="#+id/audio_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="audio Icon" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="16dp">
<TextView
android:id="#+id/song_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:textSize="16sp"
android:textStyle="bold"
android:ellipsize="marquee"
android:singleLine="true"
/>
</LinearLayout>
</LinearLayout>
I think that if you try these modifications your lists will display properly, first add this method to your adapter:
public void updateSongs(List<Songs> newSongsList) {
this.allSongs = newSongsList;
this.notifyDataSetChanged();
}
Then in the main activity:
public class MainActivity extends AppCompatActivity implements SongsAdapter.SongsViewHolder.OnSongListener {
List<Songs> songs;
//keep reference to your adapter here, instantiate in onCreate()
SongsAdapter songsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
//instantiate adapter with an empty list, update when you have data
songsAdapter = new SongsAdapter(Collections.emptyList(),MainActivity.this,MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(songsAdapter);
Dexter.withContext(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
songs= Songs.getSongs(getApplicationContext());
//now just update your list
songsAdapter.updateSongs(songs);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
})
.check();
}
#Override
public void onSongClick(int position) {
Songs currentSong = songs.get(position);
Intent intent = new Intent(MainActivity.this,PlaySongsActivity.class);
intent.putExtra("SongName",currentSong.getSongName());
intent.putExtra("Uri",currentSong.getUri());
MainActivity.this.startActivity(intent);
}
}

Can't setup my RecyclerView to display whole data from API callback

For a longer period of time, I was tried to make this app works, but unfortunately, I've stuck for good. I would like to display hourly forecast in the RecyclerView, but actually I can't, because the program will display last value of the JSON response. I've tried to print everything in console - just for testing purposes, and I've find out that if I use the for loop, then everything works just fine (but unfortunately only in the console) but as long as I don't wanted to hard code the value that I want to receive:
for(int i = 0; i<11; i++)
I wanted to do something like this:
for(int i = 0; i<list.size(); i++)
but it'll display again just one value. How I may finally solve that? Can I have any prompts? The response from the API callback is properly for sure. Here's some code:
Adapter
List<ForecastModel> forecastData = new ArrayList<>();
#NonNull
#Override
public ForecastViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.forecast_hourly, parent, false);
return new ForecastViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ForecastViewHolder holder, int position) {
ForecastModel model = forecastData.get(position);
holder.hourlyTemperature.setText(String.valueOf(model.getHourlyForecast().get(position).getTemp()));
));
}
#Override
public int getItemCount() {
return forecastData.size();
}
public void setForecastData(List<ForecastModel> list){
this.forecastData = list;
notifyDataSetChanged();
}
class ForecastViewHolder extends RecyclerView.ViewHolder {
TextView hourlyTemperature;
ForecastViewHolder(#NonNull View itemView) {
super(itemView);
hourlyTemperature = itemView.findViewById(R.id.hourly_temperature);
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ForecastViewModel mViewModel;
private List<ForecastModel> mForecastList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewModel = new ForecastViewModel(getApplication());
RecyclerView recyclerView = findViewById(R.id.forecastRecyclerView);
recyclerView.setLayoutManager( new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView.setHasFixedSize(true);
ForecastAdapter adapter = new ForecastAdapter();
recyclerView.setAdapter(adapter);
mViewModel.getForecastLiveData().observe(this, new Observer<List<ForecastModel>>() {
#Override
public void onChanged(List<ForecastModel> list) {
if (mForecastList.size() > 0){
mForecastList.clear();
}
if (list != null){
mForecastList.addAll(list);
adapter.setForecastData(mForecastList);
}
}
});
}
}
ViewModel
public class ForecastViewModel extends AndroidViewModel {
private MutableLiveData<List<ForecastModel>> forecastData;
private static ForecastRepository repository;
public ForecastViewModel(#NonNull Application application) {
super(application);
repository = ForecastRepository.getInstance();
forecastData = repository.getForecastLiveData();
}
public MutableLiveData<List<ForecastModel>> getForecastLiveData(){
return forecastData;
}
}
Repository
private static ForecastRepository instance;
private ForecastInterface api;
private ForecastRepository(){
api = ForecastRetrofitBuilder.getRetrofitBuilder();
}
public static ForecastRepository getInstance(){
if (instance == null){
instance = new ForecastRepository();
}
return instance;
}
public MutableLiveData<List<ForecastModel>> getForecastLiveData(){
MutableLiveData<List<ForecastModel>> liveData = new MutableLiveData<>();
api.getForecast(35,136,"metric", API_KEY).enqueue(new Callback<ForecastModel>() {
#Override
public void onResponse(Call<ForecastModel> call, Response<ForecastModel> response) {
if (!response.isSuccessful()){
Log.w(TAG, "onResponse: !successful "+response.code());
}
liveData.setValue(Collections.singletonList(response.body()));
}
#Override
public void onFailure(Call<ForecastModel> call, Throwable t) {
Log.w(TAG, "onFailure: "+t.getMessage());
}
});
return liveData;
}
}
ActivityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".View.MainActivity"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/forecastRecyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"/>
</LinearLayout>
forecast_hourly.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/hourly_temperature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
There could be many reasons for this, but one obvious reason is:
liveData.setValue(Collections.singletonList(response.body()));
the live data will always have a single item.
And here, you are adding that list which has a single item always, to mForecastList.
if (mForecastList.size() > 0){
mForecastList.clear();
}
if (list != null){
mForecastList.addAll(list);
adapter.setForecastData(mForecastList);
}

how to add like button in Recyclerview in android

I am a new application developer android app and need some help Please.
I need to know how to add the like button inside (Recyclerview) linked to a database (Mysql) and connect through a Volley library to save all user likes.And see how many likes each topic has.
An example that is in the picture..
I need to add it to this attached project.
MainActivity
public class MainActivity extends AppCompatActivity {
List<RecyclerViewData> recyclerViewDataList;
RecyclerView recyclerView;
private RVAdapter rvAdapter;
private static final String TAG="apple";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Employee List");
recyclerViewDataList=new ArrayList<>();
recyclerView=findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
MakeVolleyConnection();
}
private void MakeVolleyConnection() {
recyclerViewDataList = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
"http://10.0.13.45/v/parsing.php", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray dataArray = response.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject userData = dataArray.getJSONObject(i);
RecyclerViewData recyclerViewData = new RecyclerViewData();
recyclerViewData.setId(userData.getInt("id"));
recyclerViewData.setFirstname(userData.getString("first_name"));
recyclerViewData.setLastname(userData.getString("last_name"));
recyclerViewData.setAvatar(userData.getString("avatar"));
recyclerViewDataList.add(recyclerViewData);
}
rvAdapter = new RVAdapter(recyclerViewDataList, MainActivity.this);
recyclerView.setAdapter(rvAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, ""+error.networkResponse,Toast.LENGTH_SHORT).show();
}
});
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
}
MySingleton
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mContext;
private MySingleton(Context context){
// Specify the application context
mContext = context;
// Get the request queue
mRequestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context){
// If Instance is null then initialize new Instance
if(mInstance == null){
mInstance = new MySingleton(context);
}
// Return MySingleton new Instance
return mInstance;
}
public RequestQueue getRequestQueue(){
// If RequestQueue is null the initialize new RequestQueue
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
// Return RequestQueue
return mRequestQueue;
}
public<T> void addToRequestQueue(Request<T> request){
// Add the specified request to the request queue
getRequestQueue().add(request);
}
}
RecyclerViewData
public class RecyclerViewData {
private int id;
private String firstname;
private String lastname;
private String avatar;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
}
RVAdapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.RVHOLDER> {
List<RecyclerViewData> recyclerViewDataList;
Context mContext;
// Constructor with List and Context which we'll pass from RecyclerView Activity after a connection to Volley. And application context for the listener that we'll implement this later.
public RVAdapter(List<RecyclerViewData> recyclerViewDataList, Context mContext) {
this.recyclerViewDataList = recyclerViewDataList;
this.mContext = mContext;
}
// Override the method onCreateViewHolder, which will call the custom view holder that needs to be initialized. We specify the layout that each item to be used, so we can achieve this using Layout Inflator to inflate the layout and passing the output to constructor of custom ViewHolder.
#NonNull
#Override
public RVHOLDER onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.adapter_layout, viewGroup, false);
RVHOLDER rvholder = new RVHOLDER(itemView);
return rvholder;
}
//onBindViewHolder is for specifying the each item of RecyclerView. This is very similar to getView() method on ListView. In our example, this is where you need to set the user's id, name and image.
#Override
public void onBindViewHolder(#NonNull RVHOLDER rvholder, int i) {
rvholder.id.setText("User id is "+recyclerViewDataList.get(i).getId());
rvholder.first_name.setText(recyclerViewDataList.get(i).getFirstname() + " " + recyclerViewDataList.get(i).getLastname());
Picasso.get().load(recyclerViewDataList.get(i).getAvatar()).into(rvholder.avatar);
}
//We need to return the size for RecyclerView as how long a RecyclerView is, Our data is in list so passing data.size() will return the number as long as we have.
#Override
public int getItemCount() {
return recyclerViewDataList.size();
}
//This is CustomView holder that we had discuss it earlier above and inflated it in onCreateView() method. This constructor links with the xml to set the data, which we set into onBindViewHolder().
class RVHOLDER extends RecyclerView.ViewHolder {
TextView id;
private TextView first_name;
private ImageView avatar;
public RVHOLDER(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.id);
first_name = itemView.findViewById(R.id.firstname_lastname);
avatar = itemView.findViewById(R.id.avatar);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/avatar"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="16dp"
android:scaleType="fitCenter" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/firstname_lastname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceMedium" />
<TextView
android:id="#+id/id"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
<?php
$con=mysqli_connect("localhost","root","root","test");
$sql="SELECT * FROM testtable";
$result=mysqli_query($con,$sql);
$data=array();
while($row=mysqli_fetch_assoc($result)){
$data["data"][]=$row;
}
header('Content-Type:Application/json');
echo json_encode($data);
?>
#Override
public void onBindViewHolder(#NonNull RVHOLDER rvholder, int i) {
rvholder.id.setText("User id is "+recyclerViewDataList.get(i).getId());
rvholder.first_name.setText(recyclerViewDataList.get(i).getFirstname() + " " +
recyclerViewDataList.get(i).getLastname());
Picasso.get().load(recyclerViewDataList.get(i).getAvatar()).into(rvholder.avatar);
if()
}
if (recyclerViewDataList.get(i).getLiked()) {
// liked image
Picasso.get().load(gContextCompat.getDrawable(getActivity(), R.drawable.liked);).into(rvholder.like);
} else {
// without like image
Picasso.get().load(gContextCompat.getDrawable(getActivity(), R.drawable.not_like);).into(rvholder.like);
}
Add like boolean variable in RecyclerViewData Class. Add getter and setter of it. Add two drawables in drawable folder for Like and Not_like. Then Add this logic. Hope this will help. Thanks
#Override
public void onBindViewHolder(#NonNull RVHOLDER rvholder, int i) {
rvholder.id.setText("User id is "+recyclerViewDataList.get(i).getId());
rvholder.first_name.setText(recyclerViewDataList.get(i).getFirstname() + " " + recyclerViewDataList.get(i).getLastname());
Picasso.get().load(recyclerViewDataList.get(i).getAvatar()).into(rvholder.avatar);
Picasso.get().load(gContextCompat.getDrawable(getActivity(), if(recyclerViewDataList.get(i).getLiked())R.drawable.liked else R.drawable.not_like).into(rvholder.like);
}

How to open full size image when click on CardView and RecyclerView

I am trying to open a full size image when I click on CardView. I have managed to open new activity but don't know how to show image in it
NewsletterActivity.java
public class NewsletterActivity extends AppCompatActivity {
List<NewsletterAdapter> NewsletterAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL =
"http://academypk.info/eleganceschool/jsonfiles/getnewsletter.php";
String JSON_IMAGE_TITLE_NAME = "quarter";
String JSON_YEAR = "year";
String JSON_IMAGE_URL = "path";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newsletter);
NewsletterAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
NewsletterAdapter NewsletterAdapter2 = new NewsletterAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
NewsletterAdapter2.setImageTitleName(json.getString(JSON_IMAGE_TITLE_NAME));
NewsletterAdapter2.setYear(json.getString(JSON_YEAR));
NewsletterAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
NewsletterAdapter1.add(NewsletterAdapter2);
}
recyclerViewadapter = new
NewsletterRecyclerViewAdapter(NewsletterAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
NewsletterAdaptor.java
public class NewsletterAdapter {
public String ImageServerUrl;
public String ImageTitleName;
public String year;
public String getImageServerUrl() {
return ImageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.ImageServerUrl = imageServerUrl;
}
public String getImageTitleName() {
return ImageTitleName;
}
public void setImageTitleName(String ImageTitleName) {
this.ImageTitleName = ImageTitleName;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
NewsletterRecyclerViewAdaptor.java
public class NewsletterRecyclerViewAdapter extends
RecyclerView.Adapter<NewsletterRecyclerViewAdapter.ViewHolder> {
Context context;
List<NewsletterAdapter> getNewsletterAdapter;
ImageLoader imageLoader1;
public NewsletterRecyclerViewAdapter(List<NewsletterAdapter>
getNewsletterAdapter, Context context){
super();
this.getNewsletterAdapter = getNewsletterAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.newsletter_recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
NewsletterAdapter getNewsletterAdapter1 = getNewsletterAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getNewsletterAdapter1.getImageServerUrl(),
ImageLoader.getImageListener(
Viewholder.networkImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.networkImageView.setImageUrl(getNewsletterAdapter1.getImageServerUrl(), imageLoader1);
Viewholder.ImageTitleNameView.setText(getNewsletterAdapter1.getImageTitleName());
Viewholder.YearView.setText(getNewsletterAdapter1.getYear());
}
#Override
public int getItemCount() {
return getNewsletterAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public TextView YearView;
public NetworkImageView networkImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item) ;
YearView = (TextView) itemView.findViewById(R.id.textView_item1) ;
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1) ;
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), SecondPage.class);
v.getContext().startActivity(intent);
Toast.makeText(v.getContext(), "Image not found", Toast.LENGTH_SHORT).show();
}
});
}
}
}
ServerImageParseAdaptor.java
public class ServerImageParseAdapter {
public static ServerImageParseAdapter SIAdapter;
public static Context context1;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public Network networkOBJ ;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ServerImageParseAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RQ();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ServerImageParseAdapter getInstance(Context SynchronizedContext) {
if (SIAdapter == null) {
SIAdapter = new ServerImageParseAdapter(SynchronizedContext);
}
return SIAdapter;
}
public RequestQueue RQ() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
SecondPage.java
public class SecondPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_page);
}
}
Activity_Newsletter.xml
<RelativeLayout 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="info.techabyte.parentsapp.newsletter.NewsletterActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/newsletterheading"
android:background="#color/colorAccent"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/colorHeadings"
android:gravity="center_horizontal" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Newsletter_recyclerview_items.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="3dp"
card_view:contentPadding="3dp"
card_view:cardCornerRadius="3dp"
card_view:cardMaxElevation="3dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VollyNetworkImageView1"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/quarter"
android:id="#+id/textView_item"
android:layout_centerVertical="false"
android:layout_toRightOf="#+id/VollyNetworkImageView1"
android:layout_toEndOf="#+id/VollyNetworkImageView1"
android:layout_marginLeft="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/year"
android:id="#+id/textView_item1"
android:layout_centerVertical="false"
android:layout_toRightOf="#+id/VollyNetworkImageView1"
android:layout_toEndOf="#+id/VollyNetworkImageView1"
android:layout_below="#+id/textView_item"
android:layout_marginLeft="20dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
Secondpage.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#ffffff"
android:layout_height="match_parent">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VollyNetworkImageView1"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"/>
</LinearLayout>
you can use intent to pass url to other activity
like this paste belowe code where you click in cardview or in which click event your want go to other activity
Intent i = new Intent(MainActivity.this, LoginActivity.class);
i.putExtra("url", your_image_usr);
startActivity(i);
and recieve image url in your other activity like this means your imageview activity
Intent i =getIntent();
String url = i.getStringExtra("url");
and open image using this glide library to show image
compile this in your gradle file file
compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
load image like this
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
GlideApp
.with(this)
.load(url)
.centerCrop()
.placeholder(R.drawable.loading_spinner)
.into(imageView);
Here is the code where i put it
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public TextView YearView;
public NetworkImageView networkImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item) ;
YearView = (TextView) itemView.findViewById(R.id.textView_item1) ;
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1) ;
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), SecondPage.class);
intent.putExtra("path", networkImageView);
startActivity(intent);
Toast.makeText(v.getContext(), "Image not found", Toast.LENGTH_SHORT).show();
}
});
}

OnClick function on recyclerView items Of Android [duplicate]

This question already has answers here:
RecyclerView onClick
(49 answers)
Closed 6 years ago.
Hello I made a recycler view and I don't know how to configure for Onclick function on these items which can open another activity name (xyz.xml)
Main Activity.java
public class MainActivity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://platinummun.com/android_login_api/ImageJsonData.php";
String JSON_IMAGE_TITLE_NAME = "image_title";
String JSON_IMAGE_URL = "image_url";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.android_examples.recyclerviewimagelistview_android_examplescom.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
recyclerview_items.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="3dp"
card_view:contentPadding="3dp"
card_view:cardCornerRadius="3dp"
card_view:cardMaxElevation="3dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VollyNetworkImageView1"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Image Name"
android:id="#+id/textView_item"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/VollyNetworkImageView1"
android:layout_toEndOf="#+id/VollyNetworkImageView1"
android:layout_marginLeft="20dp"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
Check image here
Please help me to do it
You can try this
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private ArrayList<String> list;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView text;
public String result;
public MyViewHolder(View view) {
super(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO startintent
}
});
}
}
public MyAdapter(ArrayList<String> list) {
this.list = list;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.result = list.get(position);
holder.text.setText(list.get(position).getContentTitle());
}
#Override
public int getItemCount() {
return list.size();
}
}
You can use ItemClickSupport class to attach a listener to items in your RecyclerView
In your Adapter class,
you can implement click listener like this
#Override
public void onBindViewHolder(final YourHolder holder, final int position) {
holder.cardView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,NextActivity.class);
//if you want to pass data
intent.putExtra("hi",list.get(position).getHi());
startActivity(intent);
}
});
}
You can create an Interface in your adapter for items click.
For example:
interface ItemClickListener
{
void onItemClicked();
}
View Holder:
public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private YourModel mItem;
private ItemClickListener mItemListener;
public ItemViewHolder(View itemView, ItemClickListener listener) {
super(itemView);
ButterKnife.bind(this, itemView);
mItemListener = listener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.view_id:
mItemListener.onItemClicked(); // You can send any field or model as a param here.
break;
default:
break;
}
}
}
After that you can implement this interface in your Activity/Fragment and can write code for click event.

Categories

Resources