EventsAdapter() in EventsAdapater cannot be applied [duplicate] - java

This question already has answers here:
Using context in a fragment
(31 answers)
Closed 3 years ago.
i try to make custom listview, then I get errors, and i don't know why.
there was an error at this, R.layout.list_events_item,listEvents
and the error message is:
EventsFragment.java
public class EventsFragment extends Fragment {
private View paramView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
paramView = inflater.inflate(R.layout.fragment_events,container,false);
ListView listView = (ListView) paramView.findViewById(R.id.listViewEvents);
List<Events> listEvents = new ArrayList<Events>();
Events events = new Events(1,"12:00","A1221",
"Error at the same place","1.2.3.4","1.2.4.3","A212","123",443,1234);
listEvents.add(events);
events = new Events(2,"11:20","A1221",
"Error at the same place","1.2.3.4","1.2.4.3","A212","123",443,1234);
listEvents.add(events);
listView.setAdapter(new EventsAdapter(this, R.layout.list_events_item,listEvents));
return paramView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
}
EventsAdapter.java
public class EventsAdapter extends ArrayAdapter<Events> {
List<Events> listEvents;
Context context;
int layout;
public EventsAdapter(Context context, int layout, List<Events> listEvents){
super(context,layout,listEvents);
this.context=context;
this.layout=layout;
this.listEvents=listEvents;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
EventsHolder holder;
if (v == null){
LayoutInflater vi=((Activity)context).getLayoutInflater();
holder = new EventsHolder();
holder.time=(TextView) v.findViewById(R.id.time);
holder.signature = (TextView) v.findViewById(R.id.signatureId);
holder.sensor = (TextView) v.findViewById(R.id.sensor);
holder.attacker = (TextView) v.findViewById(R.id.attacker);
holder.attacked = (TextView) v.findViewById(R.id.attacked);
v.setTag(holder);
}else {
holder=(EventsHolder) v.getTag();
}
Events events = listEvents.get(position);
holder.time.setText(events.getTime());
holder.signature.setText(events.getSignature_id());
holder.sensor.setText(events.getSensor());
holder.attacker.setText(events.getAttacker_port());
holder.attacked.setText(events.getAttacked_port());
return v;
}
static class EventsHolder{
TextView time;
TextView signature;
TextView sensor;
TextView attacker;
TextView attacked;
}
}
my Events model
public class Events {
int id;
String time;
String signature_id;
String alert_message;
String ip_source;
String ip_destination;
String sensor;
String protocol;
int attacker_port;
int attacked_port;
public Events(int id, String time, String signature_id, String alert_message, String ip_source, String ip_destination, String sensor, String protocol, int attacker_port, int attacked_port) {
this.id = id;
this.time = time;
this.signature_id = signature_id;
this.alert_message = alert_message;
this.ip_source = ip_source;
this.ip_destination = ip_destination;
this.sensor = sensor;
this.protocol = protocol;
this.attacker_port = attacker_port;
this.attacked_port = attacked_port;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getSignature_id() {
return signature_id;
}
public void setSignature_id(String signature_id) {
this.signature_id = signature_id;
}
public String getAlert_message() {
return alert_message;
}
public void setAlert_message(String alert_message) {
this.alert_message = alert_message;
}
public String getIp_source() {
return ip_source;
}
public void setIp_source(String ip_source) {
this.ip_source = ip_source;
}
public String getIp_destination() {
return ip_destination;
}
public void setIp_destination(String ip_destination) {
this.ip_destination = ip_destination;
}
public String getSensor() {
return sensor;
}
public void setSensor(String sensor) {
this.sensor = sensor;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public int getAttacker_port() {
return attacker_port;
}
public void setAttacker_port(int attacker_port) {
this.attacker_port = attacker_port;
}
public int getAttacked_port() {
return attacked_port;
}
public void setAttacked_port(int attacked_port) {
this.attacked_port = attacked_port;
}
}

Try changing this to getActivity()

Related

Add to favorite using room Database

I'm referring this tutorial ==> https://uniqueandrocode.com/add-to-favourites-and-display-favourites-in-recyclerview/ in my project I have bottom navigation...I am trying to add favourites in the first tab and displaying favourites in the second tab in the bottom navigation bar. I'm using Room library.
When activity loads favourites are all blank at first, but when I first row as favourite and go-to favourite tab it displays properly but when I came back to the first tab it fills all the favourites icon automatically (which I have not done I had only done the first row)
Really need help. Thanks in advance.
Dao:
#Dao
public interface FavoriteDao {
#Insert
public void addData(FavoriteList favoriteList);
#Query("select * from favoritelist")
public List<FavoriteList> getFavoriteData();
#Query("SELECT EXISTS (SELECT 1 FROM favoritelist WHERE id=:id)")
public int isFavorite(int id);
#Delete
public void delete(FavoriteList favoriteList);
}
Database:
#Database(entities={FavoriteList.class},version = 1)
public abstract class FavoriteDatabase extends RoomDatabase {
public abstract FavoriteDao favoriteDao();
}
FavoriteList:
#Entity(tableName="favoritelist")
public class FavoriteList {
#PrimaryKey
private int id;
#ColumnInfo(name = "source")
private String source;
#ColumnInfo(name = "author")
private String author;
#ColumnInfo(name = "title")
private String title;
#ColumnInfo(name = "description")
private String description;
#ColumnInfo(name = "url")
private String url;
#ColumnInfo(name = "urlToImage")
private String urlToImage;
#ColumnInfo(name = "publishedAt")
private String publishedAt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
}
News fragment:
public class news extends Fragment {
ImageView favbtn;
RecyclerView recyclerView;
SwipeRefreshLayout swipeRefreshLayout;
EditText etQuery;
Button btnSearch;
Adapter adapter;
List<Articles> articles = new ArrayList<>();
public static FavoriteDatabase favoriteDatabase;
public news() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_news, container, false);
swipeRefreshLayout = view.findViewById(R.id.swiprefresh);
etQuery = view.findViewById(R.id.etQuery);
btnSearch = view.findViewById(R.id.btnSearch);
favoriteDatabase= Room.databaseBuilder(getActivity(),FavoriteDatabase.class,"myfavdb").
allowMainThreadQueries().build();
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
final String country = getCountry();
retrieveJson("", country, API_Key);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!etQuery.getText().toString().equals("")) {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson(etQuery.getText().toString(), country, API_Key);
}
});
retrieveJson(etQuery.getText().toString(), country, API_Key);
} else {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson("", country, API_Key);
}
});
retrieveJson("", country, API_Key);
}
}
});
return view;
}
private void showChangeLanguageDialog() {
}
public void retrieveJson(String query, String country, String apiKey) {
swipeRefreshLayout.setRefreshing(true);
Call<Headlines> call;
if (!etQuery.getText().toString().equals("")) {
call = ApiClient.getInstance().getApi().getSpecifiedData(query, apiKey);
} else {
call = ApiClient.getInstance().getApi().getHeadLines(country, apiKey);
}
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if (response.isSuccessful() && response.body().getArticles() != null) {
swipeRefreshLayout.setRefreshing(false);
// articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(getContext(), articles);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry() {
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final Adapter.ViewHolder holder, final int position) {
final Articles a = articles.get(position);
String imageUrl = a.getUrlToImage();
String url = a.getUrl();
holder.tvTitle.setText(a.getTitle());
Picasso.get().load(imageUrl).into(holder.imageView);
holder.tvSource.setText(a.getSource().getName());
holder.tvDate.setText(dateTime(a.getPublishedAt()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailedActivity.class);
intent.putExtra("title",a.getTitle());
intent.putExtra("source",a.getSource().getName());
intent.putExtra("time",dateTime(a.getPublishedAt()));
intent.putExtra("desc",a.getDescription());
intent.putExtra("imageUrl",a.getUrlToImage());
intent.putExtra("url",a.getUrl());
context.startActivity(intent);
}
});
if (news.favoriteDatabase.favoriteDao().isFavorite(articles.get(position).getId())==1)
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
else
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
holder.bookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FavoriteList favoriteList = new FavoriteList();
int id = articles.get(position).getId();
String source = articles.get(position).getSource().getName();
String author = articles.get(position).getAuthor();
String publishedAt = articles.get(position).getPublishedAt();
String description = articles.get(position).getDescription();
String title = articles.get(position).getTitle();
String url = articles.get(position).getUrl();
String urlToImage = articles.get(position).getUrlToImage();
favoriteList.setId(id);
favoriteList.setAuthor(author);
favoriteList.setDescription(description);
favoriteList.setSource(source);
favoriteList.setPublishedAt(publishedAt);
favoriteList.setTitle(title);
favoriteList.setUrl(url);
favoriteList.setUrlToImage(urlToImage);
favoriteList.setPublishedAt(dateTime(articles.get(position).getPublishedAt()));
if (news.favoriteDatabase.favoriteDao().isFavorite(id)!=1){
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
news.favoriteDatabase.favoriteDao().addData(favoriteList);
}else {
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
news.favoriteDatabase.favoriteDao().delete(favoriteList);
}
}
});
}
#Override
public int getItemCount() {
return articles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle, tvSource, tvDate;
ImageView imageView;
ImageButton bookmark;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvId);
tvSource = itemView.findViewById(R.id.tvSource);
tvDate = itemView.findViewById(R.id.tvDate);
imageView = itemView.findViewById(R.id.image);
cardView = itemView.findViewById(R.id.cardView);
bookmark = itemView.findViewById(R.id.favrr);
}
}
Steps to debug:
Add 2-3 items as Favs.
Restart the Application.
Check if it shows those items as fav after restarting application .
also add logs to those if conditions where you are changing the drawables.
After looking at your JSON it looks like id is what creating problems. Id is null for all your json items so when fav. one it shows fav. to all.
Solution : Use another field to check if the data is added to fav.list
Delete will not work either
Try
#Query("DELETE FROM favoritelist WHERE title = :title")
void deleteByUserId(String title);
To delete item
Also https://github.com/amitshekhariitbhu/Android-Debug-Database
check this library to debug your database

STRIKE_THRU_TEXT_FLAG not working as Expected

This is my RecyclerView Adaptor Class
public class TodoAdaptor extends RecyclerView.Adapter<TodoAdaptor.SingleTodoView> {
private CheckBox checkbox;
private TextView title, dueDate;
private Context context;
private ArrayList<SingleTodo> todoList;
private onItemCLickListener itemCLickListener;
public TodoAdaptor(Context context, ArrayList<SingleTodo> todoList, onItemCLickListener onItemClickListener) {
this.context = context;
this.todoList = todoList;
this.itemCLickListener = onItemClickListener;
}
#NonNull
#Override
public SingleTodoView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_todo, parent, false);
return new SingleTodoView(v, itemCLickListener);
}
#Override
public void onBindViewHolder(#NonNull SingleTodoView holder, int position) {
SingleTodo singleTodo = todoList.get(position);
checkbox.setChecked(singleTodo.isComplete());
title.setText(singleTodo.getTitle());
if (singleTodo.isComplete()) {
title.setPaintFlags(title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
Toast.makeText(context, "IsCompleted", Toast.LENGTH_SHORT).show();
} else {
title.setPaintFlags(title.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
Toast.makeText(context, "Not IsCompleted", Toast.LENGTH_SHORT).show();
}
if (singleTodo.getDueDate().isEmpty()) {
dueDate.setVisibility(View.GONE);
} else {
dueDate.setText(singleTodo.getDueDate());
}
}
#Override
public int getItemCount() {
return todoList.size();
}
class SingleTodoView extends RecyclerView.ViewHolder {
private SingleTodoView(#NonNull View itemView, final onItemCLickListener itemCLickListener) {
super(itemView);
checkbox = itemView.findViewById(R.id.todo_list_completed_checkbox);
title = itemView.findViewById(R.id.todo_list_title);
dueDate = itemView.findViewById(R.id.todo_list_due_date);
title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemCLickListener.onTextClickListener(getAdapterPosition());
}
});
checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemCLickListener.onCheckboxClickListener(getAdapterPosition());
}
});
}
}
public interface onItemCLickListener {
void onTextClickListener(int position);
void onCheckboxClickListener(int position);
}
}
This is My Adaptor
todoAdaptor = new TodoAdaptor(this, singleTodoArrayList, new TodoAdaptor.onItemCLickListener() {
#Override
public void onTextClickListener(int position) {
singleTodo = singleTodoArrayList.get(position);
singleTodo.setTitle("This is Test");
singleTodoArrayList.set(position, singleTodo);
todoAdaptor.notifyItemChanged(position);
}
#Override
public void onCheckboxClickListener(int position) {
singleTodo = singleTodoArrayList.get(position);
singleTodo.setComplete(!singleTodo.isComplete());
singleTodoArrayList.set(position, singleTodo);
todoAdaptor.notifyItemChanged(position);
}
});
and This is my SingleTodo Class
package com.example.simpletodo.classes;
public class SingleTodo {
private int id;
private String title;
private String dueDate;
private boolean isComplete;
public SingleTodo(int id, String title, String dueDate, boolean isComplete) {
this.id = id;
this.title = title;
this.dueDate = dueDate;
this.isComplete = isComplete;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDueDate() {
return dueDate;
}
public boolean isComplete() {
return isComplete;
}
public void setId(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setDueDate(String dueDate) {
this.dueDate = dueDate;
}
public void setComplete(boolean complete) {
isComplete = complete;
}
}
Whenever I check the checkbox, Text of that item should paint Strikethrough and Its not working as Expected
I have 3 Items in the list, when i click checkbox Item get Checked and Text Strikethrough works but when i again click checkbox checkbox stay checked (although Object is being Updated as it should be) and strikethrought text revert to normal, and i have to click checkbox twice again for check box to get unchecked
other issue is that when i checked on item and then i try to check other item, Current Item text get replaced by one of the other checked item Text.
Images :
Default:
When i click the Checkbox Once:
When i Click the Checkbox Again:
When i Checked multiple Items one by one(I have not changed position of any item before checking they was in default order and after checking --in order-- this is what i get)
Any Help is Appreciated. I just want my code to work as Expected.
I found the Solution from this Question
I had to change my Adaptor Class. I Declared Views inside my view holder class and onBindViewHolder, i am using first parameter (holder) to get my Views
public class TodoAdaptor extends RecyclerView.Adapter<TodoAdaptor.SingleTodoView> {
private boolean darkTheme;
private Context context;
private ArrayList<SingleTodo> todoList;
private onItemCLickListener itemCLickListener;
public TodoAdaptor(Context context, ArrayList<SingleTodo> todoList, boolean darkTheme, onItemCLickListener onItemClickListener) {
this.darkTheme = darkTheme;
this.context = context;
this.todoList = todoList;
this.itemCLickListener = onItemClickListener;
}
#NonNull
#Override
public SingleTodoView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.single_todo, parent, false);
return new SingleTodoView(v, itemCLickListener);
}
#Override
public void onBindViewHolder(#NonNull SingleTodoView holder, int position) {
SingleTodo singleTodo = todoList.get(position);
holder.checkbox.setChecked(singleTodo.isComplete());
holder.title.setText(singleTodo.getTitle());
if (singleTodo.isComplete()) {
holder.title.setPaintFlags(holder.title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else {
holder.title.setPaintFlags(holder.title.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
}
if (singleTodo.getDueDate().isEmpty()) {
holder.dueDate.setVisibility(View.GONE);
} else {
holder.dueDate.setVisibility(View.VISIBLE);
holder.dueDate.setText(singleTodo.getDueDate());
}
}
#Override
public int getItemCount() {
return todoList.size();
}
class SingleTodoView extends RecyclerView.ViewHolder {
private CheckBox checkbox;
private TextView title, dueDate;
private SingleTodoView(#NonNull View itemView, final onItemCLickListener itemCLickListener) {
super(itemView);
checkbox = itemView.findViewById(R.id.todo_list_completed_checkbox);
title = itemView.findViewById(R.id.todo_list_title);
dueDate = itemView.findViewById(R.id.todo_list_due_date);
if (darkTheme) {
title.setTextColor(context.getResources().getColor(R.color.colorLightGray));
dueDate.setTextColor(context.getResources().getColor(R.color.colorLightGray));
} else {
title.setTextColor(context.getResources().getColor(R.color.colorBlack));
dueDate.setTextColor(context.getResources().getColor(R.color.colorBlack));
}
title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemCLickListener.onTextClickListener(getAdapterPosition());
}
});
checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemCLickListener.onCheckboxClickListener(getAdapterPosition());
}
});
}
}
public interface onItemCLickListener {
void onTextClickListener(int position);
void onCheckboxClickListener(int position);
}
}

I want to display an image from drawable and combine it with data from json-api into recylerview

I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}

Passing data from MainActivity to Fragment

I'm trying to pass list of custom object from onDataLoaded function (which is in MainActivity) to fragment, using Parcelable. But I get this error...
This is a MainActivity funkcion, onDataLoaded
#Override
public void onDataLoaded(List<Grad> gradovi, List<Ponuda> ponude) {
Spinner spinnerGradovi = (Spinner) findViewById(R.id.gradovi_spinner);
ArrayAdapter<String> adapterGradovi;
List<String> listaGradova = new ArrayList<>();
ArrayList<Ponuda> ponudaArrayList = new ArrayList<Ponuda>();
ponudaLista = ponude;
gradLista = gradovi;
for(Grad grad : gradovi ){
listaGradova.add(grad.getNaziv());
}
for(Ponuda ponuda : ponude){
ponudaArrayList.add(ponuda);
}
//here I want to get arguments which contains ArrayList
Fragment fragmentGet = svePonudeFragment;
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Ponuda", ponudaArrayList);
fragmentGet.setArguments(bundle);
adapterGradovi = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listaGradova);
spinnerGradovi.setAdapter(adapterGradovi);
}
And this is Fragment:
public class SvePonudeFragment extends Fragment {
private RecyclerView rv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sve_ponude_fragment, container, false);
rv = (RecyclerView) rootView.findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
Bundle data = getActivity().getIntent().getExtras();
ArrayList<Ponuda> listaPonuda= data.getParcelable("ponude");
for(Ponuda ponuda : listaPonuda){
System.out.println(ponuda.getNaziv());
}
initializeAdapter(listaPonuda);
return rootView;
}
private void initializeAdapter(List<Ponuda> preuzetePonude){
RVAdapter adapter = new RVAdapter(preuzetePonude);
rv.setAdapter(adapter);
}
}
This is object class
#Table(database = MainDatabase.class)
public class Ponuda extends BaseModel implements Parcelable{
#Column
#PrimaryKey int id;
#Column String tekstPonude;
#Column int cijena;
#Column int popust;
#Column int cijenaOriginal;
#Column String urlSlike;
#Column int usteda;
#Column String kategorija;
#Column String grad;
#Column String datumPonude;
public Ponuda() {
}
public Ponuda(int id,String tekstPonude, int cijena, int popust, int cijenaOriginal, String urlSlike, int usteda, String kategorija, String grad, String datumPonude){
this.id=id;
this.tekstPonude = tekstPonude;
this.cijena = cijena;
this.popust = popust;
this.cijenaOriginal = cijenaOriginal;
this.urlSlike = urlSlike;
this.usteda = usteda;
this.kategorija = kategorija;
this.grad = grad;
this.datumPonude = datumPonude;
}
public String getNaziv() {
return tekstPonude;
}
public String getCijena() {
return Integer.toString(cijena);
}
public String getURL() {
return urlSlike;
}
public void setCijena(int cijena) {
this.cijena = cijena;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTekstPonude() {
return tekstPonude;
}
public void setTekstPonude(String tekstPonude) {
this.tekstPonude = tekstPonude;
}
public int getPopust() {
return popust;
}
public void setPopust(int popust) {
this.popust = popust;
}
public int getCijenaOriginal() {
return cijenaOriginal;
}
public void setCijenaOriginal(int cijenaOriginal) {
this.cijenaOriginal = cijenaOriginal;
}
public String getUrlSlike() {
return urlSlike;
}
public void setUrlSlike(String urlSlike) {
this.urlSlike = urlSlike;
}
public int getUsteda() {
return usteda;
}
public void setUsteda(int usteda) {
this.usteda = usteda;
}
public String getKategorija() {
return kategorija;
}
public void setKategorija(String kategorija) {
this.kategorija = kategorija;
}
public String getGrad() {
return grad;
}
public void setGrad(String grad) {
this.grad = grad;
}
public String getDatumPonude() {
return datumPonude;
}
public void setDatumPonude(String datumPonude) {
this.datumPonude = datumPonude;
}
public static List<Ponuda> getAll(){
List<Ponuda> ponudaList;
ponudaList= new Select().from(Ponuda.class).queryList();
return ponudaList;
}
public Ponuda(Parcel in){
String[] data = new String[9];
in.readStringArray(data);
this.id = in.readInt();
this.tekstPonude = in.readString();
this.cijena = in.readInt();
this.popust = in.readInt();
this.cijenaOriginal = in.readInt();
this.urlSlike = in.readString();
this.usteda = in.readInt();
this.kategorija = in.readString();
this.grad = in.readString();
this.datumPonude = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(tekstPonude);
dest.writeInt(cijena);
dest.writeInt(popust);
dest.writeInt(cijenaOriginal);
dest.writeString(urlSlike);
dest.writeInt(usteda);
dest.writeString(kategorija);
dest.writeString(grad);
dest.writeString(datumPonude);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Ponuda createFromParcel(Parcel in) {
return new Ponuda(in);
}
public Ponuda[] newArray(int size) {
return new Ponuda[size];
}
};
}
I don't understand why I get null pointer exception
Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference
Yes, you got this error. Why? because you have 2 errors:
Bundle data = getActivity().getIntent().getExtras();
-> you are trying to get bundle of your Activity, not your fragment. You should try to use getArguments() instead.
You will get another error because when your fragment's onCreateView() is called, there's no argument bundle in your fragment (your bundle is set in onDataLoaded from your activity). As my opinion you should make a reload data in your fragment like:
public void reloadData(){
//getArguments, parse and show in the list
}
//then in your onDataLoaded of MainActivity:
//here I want to get arguments which contains ArrayList
((YourFragment)fragmentGet).reloadData(); //call after set argument
You can achive this in this other way.
Getting the data from activity.
Add updateListInFragment() in your main java.
MainActivity.java
public ArrayList<Ponuda> updateListInFragment(){
return ponudaArrayList;
}
SvePonudeFragment.java
private ArrayList<Ponuda> mMyList;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sve_ponude_fragment, container, false);
rv = (RecyclerView) rootView.findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
Bundle data = getActivity().getIntent().getExtras();
updateArrayList(); //Let's update here
for(Ponuda ponuda : mMyList){
System.out.println(ponuda.getNaziv());
}
initializeAdapter(listaPonuda);
return rootView;
}
// Update your mMyList from activity
public void updateArrayList(){
MainActivity activity = (MainActivity) activity;
mMyList = activity.updateListInFragment();
}

How to set a ListView Item as checked programmatically in a BaseAdapter

Here is my CustomAdapter which extends the BaseAdpater
When i run the app i get the error
FATAL EXCEPTION: main
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.africacloudspace.apps.mobisms.adapters
This is the custom adapter
public class ContactCustomAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<ContactModel> contactModels;
boolean[] itemChecked;
public ContactCustomAdapter(Activity activity, List<ContactModel> contactModels) {
this.activity = activity;
this.contactModels = contactModels;
itemChecked = new boolean[contactModels.size()];
}
#Override
public int getCount() {
return contactModels.size();
}
#Override
public Object getItem(int location) {
return contactModels.get(location);
}
#Override
public long getItemId(int position) {
return 0;
}
private int lastPosition = -1;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolderContacts viewHolderContacts;
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.contact_item_model, null);
viewHolderContacts = new ViewHolderContacts();
viewHolderContacts.contact_id = (TextView) convertView.findViewById(R.id.item_contact_id);
viewHolderContacts.contact_fname = (TextView) convertView.findViewById(R.id.item_contact_fname);
viewHolderContacts.contact_lname = (TextView) convertView.findViewById(R.id.item_contact_lname);
viewHolderContacts.contact_number = (TextView) convertView.findViewById(R.id.item_contact_number);
viewHolderContacts.ckbox2 = (CheckBox) convertView.findViewById(R.id.checkbox_contact);
convertView.setTag(viewHolderContacts);
} else {
viewHolderContacts = (ViewHolderContacts) convertView.getTag();
}
ContactModel c = contactModels.get(position);
viewHolderContacts.contact_id.setText(c.getContactId());
viewHolderContacts.contact_fname.setText(c.getFirstName());
viewHolderContacts.contact_lname.setText(c.getLastName());
viewHolderContacts.contact_number.setText(c.getNumber());
viewHolderContacts.ckbox2.setChecked(false);
if (itemChecked[position]) {
viewHolderContacts.ckbox2.setChecked(true);
} else {
viewHolderContacts.ckbox2.setChecked(false);
}
/* animate the list items */
Animation animation = AnimationUtils.loadAnimation(parent.getContext(), (position > lastPosition) ? R.anim.list_up_from_bottom : R.anim.list_down_from_top);
convertView.startAnimation(animation);
lastPosition = position;
return convertView;
}
private class ViewHolderContacts {
TextView contact_id;
TextView contact_fname;
TextView contact_lname;
TextView contact_number;
CheckBox ckbox2;
}
}
When i remove this part from the code
if (itemChecked[position]) {
viewHolderContacts.ckbox2.setChecked(true);
} else {
viewHolderContacts.ckbox2.setChecked(false);
}
The error is gone
i have tried almost everything.. i really need some help
i am trying to implement something like this http://www.androprogrammer.com/2013/10/list-view-with-check-box-using-custom.html but i can't tell what am doing wrong.
here is my ContactModel
public class ContactModel {
public String contactId;
public String firstName;
public String lastName;
public String number;
public String email;
public String location;
public ContactModel() {
super();
}
public void setContactId(String contactId) {
this.contactId = contactId;
}
public String getContactId() {
return contactId;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setNumber(String number) {
this.number = number;
}
public String getNumber() {
return number;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
}
There is no need of taking one more boolean array to maintain the checked staus. You can achieve the same thing by taking one more variable in your ContactModel as public boolean checked;
Modify this
if (itemChecked[position]) {
viewHolderContacts.ckbox2.setChecked(true);
} else {
viewHolderContacts.ckbox2.setChecked(false);
}
as
ContactModel c = contactModels.get(position);
viewHolderContacts.ckbox2.setChecked(c.checked);
Imeplement list item click listener as follows
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
contactModels.get(position).checked = !contactModels.get(position).checked;
adapter.notifyDataSetChanged();
}
});

Categories

Resources