I'm trying to implement a feature on my application, where - if you click on a RecyclerView item - it opens up a dialog box for that item with a picture - kind of like InstaGram.
However, I am trying to make an onClickListener, where I get the position of the adapter. The goal is, that it reads what item I click on, so it can open up a dialog box for that specific item. But no matter what item in the recyclerview I click on, it returns the position as being -1.
Here is my code for it:
UserAdapter.java
import android.app.Dialog;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.myndapplication.R;
import com.example.android.myndapplication.model.User;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context mContext;
private List<User> userList;
Dialog myDialog;
public UserAdapter(Context mContext, List<User> userList) {
this.mContext = mContext;
this.userList = userList;
}
#NonNull
#Override
public UserAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_list_item, parent, false);
final ViewHolder ViewHolder = new ViewHolder(view);
ViewHolder.item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Test Click"+String.valueOf(ViewHolder.getBindingAdapterPosition()), Toast.LENGTH_SHORT).show();
}
});
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.ViewHolder holder, int position) {
User user = userList.get(position);
holder.imageView.setImageResource(userList.get(position).getImage());
holder.textView.setText(userList.get(position).getTitle());
}
#Override
public int getItemCount() {
return userList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private CardView item;
private CircleImageView iv_profile;
private TextView tv_username;
private TextView tv_date;
private ImageView iv_content;
private ImageView imageView;
private TextView textView;
public ViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.img_bookmarks);
textView = itemView.findViewById(R.id.title_bookmarks);
item = (CardView) itemView.findViewById(R.id.profile_item);
iv_profile = (CircleImageView) itemView.findViewById(R.id.dialog_profile_image);
tv_username = (TextView) itemView.findViewById(R.id.dialog_profile_username);
tv_date = (TextView) itemView.findViewById(R.id.dialog_profile_date);
iv_content = (ImageView) itemView.findViewById(R.id.dialog_content_image);
}
}
}
UserRecycler1.java
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.myndapplication.R;
import com.example.android.myndapplication.adapter.UserAdapter;
import com.example.android.myndapplication.model.User;
import java.util.ArrayList;
import java.util.List;
public class UserRecycler1 extends Fragment {
private RecyclerView recyclerView;
private UserAdapter adapter;
private List<User> userList;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userList = new ArrayList<>();
User user1 = new User(R.drawable.annapelzer, "Salad");
User user2 = new User(R.drawable.brookelark_1, "Pasta");
User user3 = new User(R.drawable.brookelark_2, "Fruit Salad");
User user4 = new User(R.drawable.brookelark_3, "Smoothies with Fruit");
User user5 = new User(R.drawable.cala, "Soup");
User user6 = new User(R.drawable.davide_cantelli, "Lobster Salad");
User user7 = new User(R.drawable.joseph_gonzales, "Breakfast toast with Berries");
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
userList.add(user5);
userList.add(user6);
userList.add(user7);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_recycler, container, false);
recyclerView = view.findViewById(R.id.recycler1);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
adapter = new UserAdapter(getActivity(), userList);
recyclerView.setAdapter(adapter);
return view;
}
}
MainFragmentTab.java
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.myndapplication.R;
import com.example.android.myndapplication.adapter.TabAdapter;
public class MainFragmentTab extends Fragment {
private TabAdapter adapter;
private TabLayout tableLayout;
private ViewPager viewPager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tabs, container, false);
viewPager = view.findViewById(R.id.request_orders_view_pager);
tableLayout = view.findViewById(R.id.request_orders_tabs);
adapter = new TabAdapter(getFragmentManager());
adapter.addFragment(new UserRecycler1(), "Public Bookmarks");
adapter.addFragment(new UserRecycler1(), "Latest Posts");
viewPager.setAdapter(adapter);
tableLayout.setupWithViewPager(viewPager);
return view;
}
}
recycler_list_item.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:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true"
app:cardCornerRadius="8dp"
android:id="#+id/profile_item">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/img_bookmarks"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/ic_launcher"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/title_bookmarks"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/title2"
android:textColor="#color/dark_green"
android:padding="5dp"
android:textSize="16sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
I hope you all can help, as I have tried for a while, but continue to receive the same output no matter what I do.
You have to move your setOnClickListener from onCreateViewHolder into onBindViewHolder.
You might want to check this tutorial
Edit
Something like here:
#NonNull
#Override
public UserAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_list_item, parent, false);
final ViewHolder ViewHolder = new ViewHolder(view);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.ViewHolder holder, int position) {
User user = userList.get(position);
holder.imageView.setImageResource(userList.get(position).getImage());
holder.textView.setText(userList.get(position).getTitle());
holder.item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Test Click"+userList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
Related
I am absolute beginner for this, I'm sorry if this such a dumb mistakes.
so, I created fragment in which i have got recyclerView, but my recycler view is empty, i saw that my context is empty, and i think, that it can be the reason of this, i try to use getActivity
here is code of my fragment
package com.example.pocketcinema;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
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 com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class SearchFragment extends Fragment implements RecyclerViewInterface {
private RecyclerView recyclerView;
RecyclerViewInterface rci;
MyAdapter myAdapter;
public List<String> nameOfFilm, youTubeUrl, photoUrl, descriptionToFilm, category;
FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
recyclerView = inflater.inflate(R.layout.fragment_search, container,
false).findViewById(R.id.filmsList);
rci = this;
nameOfFilm = new ArrayList<>();
youTubeUrl = new ArrayList<>();
photoUrl = new ArrayList<>();
descriptionToFilm = new ArrayList<>();
category = new ArrayList<>();
loadFilmsFromDB();
return inflater.inflate(R.layout.fragment_search, container, false);
}
private void loadFilmsFromDB() {
Context context = requireContext();
db.collection("films").get().addOnCompleteListener(new
OnCompleteListener<QuerySnapshot>()
{
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
for (QueryDocumentSnapshot document : task.getResult()) {
nameOfFilm.add(document.get("nameOfFilm").toString());
descriptionToFilm.add(document.get("descriptionToFilm").toString());
photoUrl.add(document.get("imageUrl").toString());
youTubeUrl.add(document.get("videoURL").toString());
category.add(document.get("category").toString());
myAdapter = new MyAdapter(context, nameOfFilm, descriptionToFilm,
photoUrl, youTubeUrl,
rci, category);
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
}
}
});
}
here is screenshot with debuger, you can see that context = null
context = null
here you can see that i set layout for recyclerView
with logcat
here is Adapter
package com.example.pocketcinema;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class MyAdapter extends
RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context ct;
List<String> name, description, image, video, category;
private final RecyclerViewInterface recyclerViewInterface;
public MyAdapter(Context ct, List<String> nameOfFilm, List<String>
descriptionOfFilm, List<String> imageUrl, List<String> videoUrl,
RecyclerViewInterface rci,List<String> category) {
name = nameOfFilm;
description = descriptionOfFilm;
image = imageUrl;
video = videoUrl;
this.ct = ct;
recyclerViewInterface = rci;
this.category = category;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
LayoutInflater inflater = LayoutInflater.from(ct);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view, recyclerViewInterface);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int
position) {
holder.nameFilm.setText(name.get(position));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ct, PlayerActivity.class);
}
});
Picasso.get().load(image.get(position)).into(holder.image2);
}
#Override
public int getItemCount() {
return image.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView nameFilm;
ImageView image2;
CardView cardView;
public MyViewHolder(#NonNull View itemView, RecyclerViewInterface
recyclerViewInterface) {
super(itemView);
nameFilm = itemView.findViewById(R.id.nameTV);
image2 = itemView.findViewById(R.id.imageView2);
cardView = itemView.findViewById(R.id.cardView);
itemView.findViewById(R.id.sectionOFRecyclerView).setOnClickListener
(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recyclerViewInterface != null) {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
recyclerViewInterface.onItemClick(pos);
}
}
}
});
}
}
}
myAdapter isn't null
You are trying to create an instance of activity as global variable. That means the context has not been generated yet.
Basically you can just use requireContext() method of Fragment class. This will provide you the context.
As I have mentioned in comment, you need to update your onCreateView method as below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_search, container, false);
}
Then, you need to initialize your view and other stuff on onViewCreated method. You can update that method like this:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = view.findViewById(R.id.filmsList);
textView = view.findViewById(R.id.test);
rci = this;
nameOfFilm = new ArrayList<>();
youTubeUrl = new ArrayList<>();
photoUrl = new ArrayList<>();
descriptionToFilm = new ArrayList<>();
category = new ArrayList<>();
loadFilmsFromDB();
}
Notes
You don't have to send many string parameters to your adapter. It is better to create a Model class for that item, and send the list of that item. So, model classes will have all the data you need, and you can use them from that model. This will give you better coding style and will let you manage your data easier.
To communicate with your XML layout, you can use ViewBinding or DataBinding for that. This will also help you to use your view elements without creating variables for each of them.
I am working on a chat app with firebase and I want to fitch the user information to the recyclerview...my code is correct by when I set the adapter to the recycler view its show an error.
Here is my code:
package com.abdelatif.chatapp;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.squareup.picasso.Picasso;
public class ChatFragment extends Fragment {
private FirebaseFirestore firebaseFirestore;
LinearLayoutManager linearLayoutManager;
private FirebaseAuth firebaseAuth;
ImageView mimageviewofuser;
FirestoreRecyclerAdapter<FireBaseModel, NoteViewHolder> chatAdapter = null;
RecyclerView mrecyclerview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.chatfragment,container,false);
firebaseAuth=FirebaseAuth.getInstance();
firebaseFirestore= FirebaseFirestore.getInstance();
mrecyclerview=v.findViewById(R.id.recyclerView);
// Query query=firebaseFirestore.collection("Users");
Query query=firebaseFirestore.collection("Users").whereNotEqualTo("uid",firebaseAuth.getUid());
FirestoreRecyclerOptions<FireBaseModel> allusername=new FirestoreRecyclerOptions.Builder<FireBaseModel>().setQuery(query,FireBaseModel.class).build();
chatAdapter=new FirestoreRecyclerAdapter<FireBaseModel, NoteViewHolder>(allusername) {
#Override
protected void onBindViewHolder(#NonNull NoteViewHolder noteViewHolder, int i, #NonNull FireBaseModel firebasemodel) {
noteViewHolder.particularusername.setText(firebasemodel.getName());
String uri=firebasemodel.getImage();
Picasso.get().load(uri).into(mimageviewofuser);
if(firebasemodel.getStatus().equals("Online"))
{
noteViewHolder.statusofuser.setText(firebasemodel.getStatus());
noteViewHolder.statusofuser.setTextColor(Color.GREEN);
}
else
{
noteViewHolder.statusofuser.setText(firebasemodel.getStatus());
}
noteViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "contactClicked", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_view_layout,parent,false);
return new NoteViewHolder(view);
}
};
mrecyclerview.setHasFixedSize(true);
linearLayoutManager=new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
mrecyclerview.setLayoutManager(linearLayoutManager);
mrecyclerview.setAdapter(chatAdapter);
chatAdapter.startListening();
return v;
}
public class NoteViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder
{
private TextView particularusername;
private TextView statusofuser;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
particularusername=itemView.findViewById(R.id.nameOfUser);
statusofuser=itemView.findViewById(R.id.statusOfUser);
mimageviewofuser=itemView.findViewById(R.id.imageViewOfUser);
}
}
}
the error is in the line: mrecyclerview.setAdapter(chatAdapter);
and the error is:
'setAdapter(androidx.recyclerview.widget.RecyclerView.Adapter)' in 'androidx.recyclerview.widget.RecyclerView' cannot be applied to '(com.firebase.ui.firestore.FirestoreRecyclerAdapter<com.abdelatif.chatapp.FireBaseModel,com.abdelatif.chatapp.ChatFragment.NoteViewHolder>)'
I hope someone give me a solution...i searched many time but nothing.
Make sure you call chatAdapter.startListening(); before calling mrecyclerview.setAdapter(chatAdapter);
i have tried several methods to make my items clickable i have read about focus and added the lines in my XML file Relative layout. nothing seems to help. the click listener still doesn't seem to do anything for me.. please help!!!
this is my activity list view class:
package com.example.trezah12.adminmodule;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class AdminList extends AppCompatActivity {
CustomAdapterAdmin adapterAdmin;
ArrayList<Admin> list;
ListView list1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_list);
DBhandler dBhandler = new DBhandler(this);
list = new ArrayList<>();
list1 = (ListView) findViewById(R.id.listview4);
viewData();
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long Id) {
Intent intent = new Intent(AdminList.this, LaunchActivity.class);
}
});
}
private void viewData() {
final DBhandler dbHandler3 = new DBhandler(AdminList.this);
Cursor cursor = dbHandler3.viewData();
if (cursor.getCount() == 0){
Toast toast = Toast.makeText(getApplicationContext(), "Sorry no Data Found!!", Toast.LENGTH_SHORT);
}
else {
while (cursor.moveToNext()) {
Admin admin = new Admin();
admin.setUsername(cursor.getString(0));
list.add(admin);
list1 = (ListView) findViewById(R.id.listview4);
adapterAdmin = new CustomAdapterAdmin(list, AdminList.this);
list1.setAdapter(adapterAdmin);
}
}
}
}
below is my custom adapter class for admin:
package com.example.trezah12.adminmodule;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by trezah12 on 23/10/2018.
*/
public class CustomAdapterAdmin extends BaseAdapter {
private List<Admin> adminList = new ArrayList<Admin>();
private Context activity;
private static LayoutInflater inflater = null;
public CustomAdapterAdmin(List<Admin> adminList, Context activity) {
this.adminList = adminList;
this.activity = activity;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return adminList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) {
v = inflater.inflate(R.layout.customeadmin, null);
}
Admin admin = adminList.get(position);
TextView txt1 = (TextView) v.findViewById(R.id.textView1);
txt1.setText(admin.getUsername());
TextView txt2 = (TextView) v.findViewById(R.id.textView2);
txt2.setText(admin.getPassword());
return v;
}
}
Below is my XML file for list view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#+id/listview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</ListView>
</RelativeLayout>
that is because yout did not start the activity
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long Id) {
Intent intent = new Intent(AdminList.this, LaunchActivity.class);
startActivity(intent);
}
});
I have a recyclerView that must show a list of cards, but it doesn't!
There is an arrayList of recipes get passed to the adapter to display them as cardviews, everything in the debugging seems to be alright, but it doesnt display anything on the screen.
ViewHolder:
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.nd.ameer.bake.R;
public class RecipeViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView;
public ImageView coverImageView;
public RecipeViewHolder(View v) {
super(v);
titleTextView = (TextView) v.findViewById(R.id.titleTextView);
coverImageView = (ImageView) v.findViewById(R.id.recipeImageView);
}
}
Adapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.example.nd.ameer.bake.R;
import com.example.nd.ameer.bake.models.Recipe;
import com.example.nd.ameer.bake.views.holders.RecipeViewHolder;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class RecipeAdapter extends
RecyclerView.Adapter<RecipeViewHolder> {
ArrayList<Recipe> recipes = new ArrayList<>();
Context context;
public RecipeAdapter(ArrayList<Recipe> recipes, Context context) {
this.recipes = recipes;
this.context = context;
}
#Override
public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recipe_item, parent, false);
return new RecipeViewHolder(view);
}
#Override
public void onBindViewHolder(RecipeViewHolder holder, int position) {
holder.coverImageView.setImageResource(R.color.colorPrimaryLight);
holder.titleTextView.setText(recipes.get(position).getName());
}
#Override
public int getItemCount() {
return recipes.size();
}
}
Fragment onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_recipe, container, false);
createRecipes();
recyclerView = (RecyclerView) rootView.findViewById(R.id.rv_recipe);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
if (recipes.size() > 0 & recyclerView != null) {
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(new RecipeAdapter(recipes, getContext()));
}
return rootView;
}
The method createRecipes(); creates a list of recipes and then it get passed to the adapter.
as you can see, the recipes size is 4, so it's not the problem
I didn't know the cause of the problem till now, but I moved both the adapter and the view holder to the Recipes Fragment as inner classes, and this has fixed the problem.
I am creating an News app, am a newbie, Have some errors in MainActivity.Java i couldn't resolve them. Need help!
This is My MainActivity.Java
package com.example.arumugam.newsreader;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.lang.String;
import java.util.List;
public class MainActivity extends Fragment {
public MainActivity() {
// Required empty public constructor
}
private List<newsItem> newsFeed = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_main, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("News");
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
"https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson.json",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray newsItem = response.getJSONArray("newsItems");
for (int i = 0; i < newsItem.length(); i++) {
JSONObject temp = newsItem.getJSONObject(i);
String title = temp.getString("title");
String description = temp.getString("description");
String url = temp.getString("url");
String urlToImage = temp.getString("urlToImage");
newsFeed.add(new newsItem(title, description, url, urlToImage));
}
} catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(newsReq);
ArrayAdapter<newsItem> adapter = new customAdapter(newsFeed,getActivity());
ListView newsItems =(ListView) (getActivity().findViewById(R.id.newsItems));
newsItems.setAdapter(adapter);
}
private class customAdapter extends ArrayAdapter<newsItem>{
Activity context;
customAdapter(List<newsItem> newsFeed, Activity context) {
super(getActivity(), R.layout.item, newsFeed);
this.context = context;
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.item, parent, false);
}
newsItem currentItem = newsFeed.get(position);
ImageView newsImage = (ImageView) convertView.findViewById(R.id.leftIco);
TextView newsHeading = (TextView) convertView.findViewById(R.id.heading);
TextView newsDesc = (TextView) convertView.findViewById(R.id.desc);
newsImage.setImageResource(R.mipmap.ic_launcher);
newsHeading.setText(currentItem.getNewsHeading());
newsDesc.setText(String.valueOf((currentItem.getNewsDesc())));
return convertView;
}
}
}
This is my newsItem.java
public class newsItem {
private String newsHeading;
private String newsDesc;
private String newsDescSmall;
private String time;
private String date;
private String url;
private String imageURL;
public newsItem(String newsHeading, String newsDesc, String date, String time) {
this.newsHeading = newsHeading;
this.newsDesc = newsDesc;
this.time = time;
this.date = date;
this.url = url;
this.imageURL = imageURL;
this.newsDescSmall = this.newsDesc.substring(0, 50) + "...";
}
public String getNewsHeading() {
return newsHeading;
}
public String getNewsDesc() {
return newsDesc;
}
public String getNewsDescSmall() {
return newsDescSmall;
}
public String getTime() {
return time;
}
public String getDate() {
return date;
}
public String getUrl() {
return url;
}
public String getImageURL() {
return imageURL;
}
}
This is my item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/leftIco"
android:src="#mipmap/ic_launcher"
android:maxHeight="70dp"
android:maxWidth="70dp"
android:adjustViewBounds="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Description"
android:lineSpacingExtra="-3dp"
android:id="#+id/desc"
android:layout_alignBottom="#+id/leftIco"
android:layout_alignLeft="#+id/heading"
android:layout_alignStart="#+id/heading" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Heading Text"
android:textStyle="bold"
android:id="#+id/heading"
android:scrollHorizontally="true"
android:maxLines="1"
android:layout_marginBottom="15dp"
android:ellipsize="end"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/leftIco"
android:layout_toEndOf="#+id/leftIco"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp" />
</RelativeLayout>
The problem i am facing is with this line
ArrayAdapter<newsItem> adapter = new customAdapter(newsFeed,getActivity());
Thank you in advance..
Error on Android Studio
Logcat Error
05-10 19:39:01.191 1232-1318/system_process E/Parcel: Class not found when unmarshalling: com.truecaller.service.MissedCallReminder
java.lang.ClassNotFoundException: com.truecaller.service.MissedCallReminder
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:400)
at android.os.Parcel.readParcelableCreator(Parcel.java:2508)
at android.os.Parcel.readParcelable(Parcel.java:2462)
at android.os.Parcel.readValue(Parcel.java:2365)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2732)
at android.os.BaseBundle.unparcel(BaseBundle.java:268)
at android.os.Bundle.putAll(Bundle.java:226)
at android.content.Intent.fillIn(Intent.java:8273)
at
com.android.server.am.PendingIntentRecord.sendInner(PendingIntentRecord.java:244)
at com.android.server.am.PendingIntentRecord.sendWithResult(PendingIntentRecord.java:205)
at com.android.server.am.ActivityManagerService.sendIntentSender(ActivityManagerService.java:7305)
at android.app.PendingIntent.send(PendingIntent.java:836)
at com.android.server.AlarmManagerService$DeliveryTracker.deliverLocked(AlarmManagerService.java:3187)
at com.android.server.AlarmManagerService.deliverAlarmsLocked(AlarmManagerService.java:2620)
at com.android.server.AlarmManagerService$AlarmThread.run(AlarmManagerService.java:2741)
Caused by: java.lang.ClassNotFoundException: com.truecaller.service.MissedCallReminder
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:1346)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:1406)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:400)
at android.os.Parcel.readParcelableCreator(Parcel.java:2508)
at android.os.Parcel.readParcelable(Parcel.java:2462)
at android.os.Parcel.readValue(Parcel.java:2365)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2732)
at android.os.BaseBundle.unparcel(BaseBundle.java:268)
at android.os.Bundle.putAll(Bundle.java:226)
at android.content.Intent.fillIn(Intent.java:8273)
at com.android.server.am.PendingIntentRecord.sendInner(PendingIntentRecord.java:244)
at com.android.server.am.PendingIntentRecord.sendWithResult(PendingIntentRecord.java:205)
at com.android.server.am.ActivityManagerService.sendIntentSender(ActivityManagerService.java:7305)
at android.app.PendingIntent.send(PendingIntent.java:836)
at com.android.server.AlarmManagerService$DeliveryTracker.deliverLocked(AlarmManagerService.java:3187)
at com.android.server.AlarmManagerService.deliverAlarmsLocked(AlarmManagerService.java:2620)
at com.android.server.AlarmManagerService$AlarmThread.run(AlarmManagerService.javat:2741)
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
You should change in customAdapter class
customAdapter(List<newsItem> newsFeed, Context context) {
super(getActivity(), R.layout.item, newsFeed);
this.context = context;
}
and it will work definitely....
i hope this answer help you..
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.lang.String;
import java.util.List;
public class MainActivity extends Fragment {
private List<newsItem> newsFeed = new ArrayList<>();
public MainActivity() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.activity_main, container, false);
getActivity().setTitle("News");
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
"https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson.json",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray newsItem = response.getJSONArray("newsItems");
for (int i = 0; i < newsItem.length(); i++) {
JSONObject temp = newsItem.getJSONObject(i);
String title = temp.getString("title");
String description = temp.getString("description");
String url = temp.getString("url");
String urlToImage = temp.getString("urlToImage");
newsFeed.add(new newsItem(title, description, url, urlToImage));
ArrayAdapter<newsItem> adapter = new customAdapter(newsFeed,getActivity());
ListView newsItems =(ListView) (getActivity().findViewById(R.id.newsItems));
newsItems.setAdapter(adapter);
}
} catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(newsReq);
return view;
}
private class customAdapter extends ArrayAdapter<newsItem>{
Context context;
customAdapter(List<newsItem> newsFeed, Context context) {
super(getActivity(), R.layout.item, newsFeed);
this.context = context;
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
newsItem currentItem = newsFeed.get(position);
if (convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.item, parent, false);
}
ImageView newsImage = (ImageView) convertView.findViewById(R.id.leftIco);
TextView newsHeading = (TextView) convertView.findViewById(R.id.heading);
TextView newsDesc = (TextView) convertView.findViewById(R.id.desc);
newsImage.setImageResource(R.mipmap.ic_launcher);
newsHeading.setText(currentItem.getNewsHeading());
newsDesc.setText(String.valueOf((currentItem.getNewsDesc())));
return convertView;
}
}
}
Found the solution finally.
Modified MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.lang.String;
import java.util.List;
import static android.view.LayoutInflater.from;
public class MainActivity extends AppCompatActivity {
private List<newsItem> newsFeed = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
engine();
MainActivity.this.setTitle("News");}
private void engine() {
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
"https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson.json",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray newsItem = response.getJSONObject("root").getJSONArray("articles");
for (int i = 0; i < newsItem.length(); i++) {
JSONObject temp = newsItem.getJSONObject(i);
String title = temp.getString("title");
String description = temp.getString("description");
String url = temp.getString("url");
String urlToImage = temp.getString("urlToImage");
newsFeed.add(new newsItem(title, description, url, urlToImage));
}
RecyclerView.Adapter adapter = new customAdapter(MainActivity.this,newsFeed);
RecyclerView newsItems =(RecyclerView) findViewById(R.id.newsItems);
LinearLayoutManager llm=new
LinearLayoutManager(MainActivity.this);
newsItems.setLayoutManager(llm);
newsItems.setAdapter(adapter);
} catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(newsReq);
}
private class customAdapter extends RecyclerView.Adapter<MyViewHolder> {
private final List<newsItem> newsfeedlist;
public customAdapter(MainActivity mainActivity, List<newsItem> newsFeed) {
this.newsfeedlist= newsFeed;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = getLayoutInflater().from(parent.getContext()).inflate(R.layout.item,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
newsItem items = newsfeedlist.get(position);
holder.newsImage.setImageResource(R.mipmap.ic_launcher);
holder.newsHeading.setText(items.getNewsHeading());
holder.newsDesc.setText(items.getNewsDesc());
}
#Override
public int getItemCount() {
return newsfeedlist.size();
}
}
private class MyViewHolder extends RecyclerView.ViewHolder{
public ImageView newsImage;
public TextView newsHeading;
public TextView newsDesc;
public MyViewHolder(View itemView) {
super(itemView);
newsImage = (ImageView) itemView.findViewById(R.id.leftIco);
newsHeading = (TextView) itemView.findViewById(R.id.heading);
newsDesc = (TextView) itemView.findViewById(R.id.desc);
}
}
}
Changed fragments to Activity and changed ArrayAdapter to Recycler view
Please share your customAdapter code or refer this tutorial
Listview with customadapter
Note: use recylerView in place of the listview for better performance.
Create a volley singleton class.