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.
Related
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);
}
}
I want to implement an onClickListener for a RecyclerViewItem in my App. My problem is, that the onclick listener isn't being called. Not even in the adapter. I'm trying to get this to work for 5 hours now and I'm really frustrated and don't know how to fix this/proceed.
I hope you can help me.
ItemListAdapter.class
public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.ItemViewHolder> implements Filterable {
private ArrayList<Item> mItemList;
private ArrayList<Item> mItemListFiltered;
private ItemsListAdapterListener mItemsListAdapterListener;
public ItemListAdapter(ArrayList<Item> itemArrayList, ItemsListAdapterListener itemsListAdapterListener) {
mItemList = itemArrayList;
mItemListFiltered = itemArrayList;
this.mItemsListAdapterListener = itemsListAdapterListener;
}
public interface ItemsListAdapterListener {
void onItemClick(int position);
}
public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView mImageView;
public TextView mTextView;
ItemsListAdapterListener mItemsListAdapterListener;
public ItemViewHolder(#NonNull View itemView, ItemsListAdapterListener itemsListAdapterListener) {
super(itemView);
mItemsListAdapterListener = itemsListAdapterListener;
mImageView = itemView.findViewById(R.id.imageViewItem);
mTextView = itemView.findViewById(R.id.textViewItem);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mItemsListAdapterListener.onItemClick(getAdapterPosition());
Log.i("test", "Adapter click");
}
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_view_layout, parent, false);
ItemViewHolder itemViewHolder = new ItemViewHolder(view, mItemsListAdapterListener);
return itemViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
Item item = mItemListFiltered.get(position);
holder.mImageView.setImageResource(item.getImgURL());
holder.mTextView.setText(item.getItemName());
}
#Override
public int getItemCount() {
return mItemListFiltered.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
mItemListFiltered = mItemList;
} else {
ArrayList<Item> filteredList = new ArrayList<>();
for (Item row: mItemList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getItemName().toLowerCase().contains(charString.toLowerCase()) || row.getItemCategory().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
mItemListFiltered = (ArrayList<Item>) filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mItemListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mItemListFiltered = (ArrayList<Item>) filterResults.values;
notifyDataSetChanged();
}
};
}
}
ItemsFragment.class
public class ItemsFragment extends Fragment implements TextWatcher, ItemListAdapter.ItemsListAdapterListener{
private ItemsViewModel itemsViewModel;
private RecyclerView mRecyclerView;
private ItemListAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public View onCreateView(#NonNull final LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
itemsViewModel =
ViewModelProviders.of(this).get(ItemsViewModel.class);
View root = inflater.inflate(R.layout.fragment_items, container, false);
final EditText editTextItemSearch;
editTextItemSearch = (EditText) root.findViewById(R.id.editTextItemSearch);
editTextItemSearch.addTextChangedListener(this);
final ArrayList<Item> itemArrayList = new ArrayList<>();
itemArrayList.add(new Item("TestItem1", R.drawable.unbenannt, getString(R.string.item_parts)));
itemArrayList.add(new Item("TestItem2", R.drawable.ic_home_black_24dp, getString(R.string.item_tools)));
itemArrayList.add(new Item("TestItem3", R.drawable.ic_dashboard_black_24dp, getString(R.string.item_consumable)));
itemArrayList.add(new Item("test123", R.drawable.ic_notifications_black_24dp, getString(R.string.item_interactive)));
itemArrayList.add(new Item("test12567687863", R.drawable.ic_notifications_black_24dp,getString(R.string.item_blocks)));
Log.i("test", "items added");
mRecyclerView = root.findViewById(R.id.recylcerViewItems);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
mAdapter = new ItemListAdapter(itemArrayList, this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
return root;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mAdapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void onItemClick(int position) {
Log.i("test", "item clicked");
}
}
adapter_view_layout.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"
android:layout_marginBottom="6dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_margin="8dp"
android:backgroundTint="#color/colorBackroundBright"
android:clickable="true"
android:foreground="?attr/selectableItemBackground"
app:cardCornerRadius="15dp"
tools:layout_editor_absoluteX="144dp"
tools:layout_editor_absoluteY="42dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageViewItem"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_margin="16dp"
android:layout_marginStart="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textViewItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:fontFamily="#font/nunito_regular"
android:text="ItemName"
android:textColor="#959595"
app:layout_constraintBottom_toBottomOf="#+id/imageViewItem"
app:layout_constraintStart_toEndOf="#+id/imageViewItem"
app:layout_constraintTop_toTopOf="#+id/imageViewItem" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
Try removing android:clickable="true" from your CardView.
I think what is happening is you are clicking on the CardView, which is stealing the click so the root view does not get it.
Try this:
In ItemViewHolder add a View object and set it to itemView:
public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView mImageView;
public TextView mTextView;
//add here
public View view;
ItemsListAdapterListener mItemsListAdapterListener;
public ItemViewHolder(#NonNull View itemView, ItemsListAdapterListener itemsListAdapterListener) {
super(itemView);
//set here
view = itemView;
.........
.........
Now set the onClickListener in onBindViewHolder:
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
Item item = mItemListFiltered.get(position);
holder.mImageView.setImageResource(item.getImgURL());
holder.mTextView.setText(item.getItemName());
//here
holder.view.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
mItemsListAdapterListener.onItemClick(position);
}
});
}
UPDATE:
Remove this from cardView xml:
android:clickable="true"
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();
}
});
}
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.
I am building a sudoku in android ,so how do i register all the textviews
for e.g :
button1=(Button)findViewByid(R.id.btn1)
Do i need to write 81 such statements to register every TextView
you can add the views in java code when app running.
you can write your textview's xml statement in an xml file alone, and then inflate it.
In this way, you don't need the view id, because you already have its reference.
grid.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...
/>
MyActivity.java
ArrayList<TextView> list = new ArrayList<>();
for (int i = 0; i < 81; i++) {
TextView view = (TextView)LayoutInflater.from(ItemDragAndSwipeUseActivity.this).inflate(R.layout.grid, null);
list.add(view);
}
// then attach these views to the layout with addView()
you can use grid view with an adapter instead of text views
grid item
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="13sp"
android:text="#string/country_name"
android:textColor="#color/accent_color"
android:gravity="center"
android:paddingBottom="8dp"
android:paddingTop="8dp"
android:background="#color/color_primary_dark"/>
</RelativeLayout>
Adapter class
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
holder.textView.setText(itemList.get(position).getName());
}
#Override
public int getItemCount() {
return this.itemList.size();
}
public class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView textView;
public RecyclerViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
textView = (TextView)itemView.findViewById(R.id.textView);
}
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked Position = " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
}
Activity class
public class MainActivity extends ActionBarActivity {
private GridLayoutManager lLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle(null);
Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
topToolBar.setLogo(R.drawable.logo);
topToolBar.setLogoDescription(getResources().getString(R.string.logo_desc));
List<ItemObject> rowListItem = getAllItemList();
lLayout = new GridLayoutManager(MainActivity.this, 4);
RecyclerView rView = (RecyclerView)findViewById(R.id.recycler_view);
rView.setHasFixedSize(true);
rView.setLayoutManager(lLayout);
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(MainActivity.this, rowListItem);
rView.setAdapter(rcAdapter);
}
private List<ItemObject> getAllItemList(){
List<ItemObject> allItems = new ArrayList<ItemObject>();
allItems.add(new ItemObject("1");
allItems.add(new ItemObject("2");
allItems.add(new ItemObject("3");
return allItems;
}
}
You don't have to use IDs for this. You can just create a View (Container) in XML and fill it using a for loop completely without using IDs. You can access them afterwards via their index in the Container.
I hope this helped.