I have a tabLayout in which there is Log Fragment tab it store all the incoming calls details in LogsData List Object and set .
New callLogs is updated after App close and restart but I want to refresh my RecyclerView when the call is in ringing state.
My LogFragment
public class LogsFragment extends Fragment {
private RecyclerView mRecyclerView;
private ListAdapter mListadapter;
ArrayList data;
TinyDB tinyDB;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_call_log, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
tinyDB = new TinyDB(getContext());
data = tinyDB.getListObject("LogData", LogsData.class);
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setHasFixedSize(false);
mRecyclerView.setLayoutManager(layoutManager);
data = tinyDB.getListObject("LogData", LogsData.class);
mListadapter = new ListAdapter(data);
mListadapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mListadapter);
return view;
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMyEvent(Object o) {
/* Refresh your adapter */
data = tinyDB.getListObject("LogData", LogsData.class);
mListadapter = new ListAdapter(data);
mListadapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mListadapter);
};
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> {
private ArrayList<LogsData> dataList;
public ListAdapter(ArrayList<LogsData> data) {
this.dataList = data;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textViewName;
TextView textViewNumb;
TextView textViewTime;
public ViewHolder(View itemView) {
super(itemView);
this.textViewName = itemView.findViewById(R.id.cName);
this.textViewNumb = itemView.findViewById(R.id.number);
this.textViewTime = itemView.findViewById(R.id.time_stamp);
}
}
#Override
public ListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.log_list, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.textViewName.setText(dataList.get(position).getName());
holder.textViewNumb.setText(dataList.get(position).getNumber());
holder.textViewTime.setText(dataList.get(position).getTime());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Item " + position + " is clicked.", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return dataList.size();
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMyEvent(Object o) {
/* Refresh your adapter */
data = tinyDB.getListObject("LogData", LogsData.class);
mListadapter = new ListAdapter(data);
mListadapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mListadapter);
};
}
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
}
And my PhoneStateReceiver Class
public class PhoneStateReceiver extends BroadcastReceiver {
public final static String TAG = "SSD";
String incomingNumber;
String state;
DateFormat timeFormat;
Context context;
String date;
String cName;
ArrayList data;
#SuppressLint("UnsafeProtectedBroadcastReceiver")
#Override
public void onReceive(Context context, Intent intent) {
TinyDB tinydb = new TinyDB(context);
data = tinydb.getListObject("LogData", LogsData.class);
try {
state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
cName = getContactName(incomingNumber, context);
timeFormat = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
date = timeFormat.format(Calendar.getInstance().getTime());
Log.d(TAG, date);
String phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
data.add(new LogsData(cName, incomingNumber, date));
tinydb.putListObject("LogData", data);
Toast.makeText(context, date + " " + incomingNumber + " " + cName, Toast.LENGTH_SHORT).show();
}
EventBus.getDefault().post(new Object());
} catch (Exception e) {
e.printStackTrace();
}
}
public String getContactName(final String phoneNumber, Context context) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};
String contactName = "";
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
contactName = cursor.getString(0);
}
cursor.close();
}
return contactName;
}
}
I update my codes please see it.
Use EventBus to do it
In your LogsFragment prepare subscriber like this:
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMyEvent(Object o) {
/* Refresh your adapter */
data = tinyDB.getListObject("LogData", LogsData.class);
mListadapter = new ListAdapter(data);
mListadapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mListadapter);
};
And in your PhoneStateReceiver call your subscriber like this:
EventBus.getDefault().post(new Object());
Do not forget to register and unregister your subscriber in LogsFragment
You can read more about EventBus in here
Related
How can I refresh the RecyclerView after adding a new item, Note that I'm using a hub connection to send and receive messages from the back-end side, and I'm trying to use notifyItemRangeChanged to refresh the RecyclerView but it does not work,
Here is the adapter class:
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
public static int i = 0;
private Context mContext;
private List<Chat> mChat;
private String imageurl;
public MessageAdapter(Context mContext, List<Chat> mChat, String imageurl) {
this.mContext = mContext;
this.mChat = mChat;
this.imageurl = imageurl;
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if(viewType == MSG_TYPE_RIGHT){
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdapter.ViewHolder(view);
}else{
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat = mChat.get(position);
holder.show_message.setText(chat.getMessage());
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
holder.setItem_on_click_listener(new item_on_click_listener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
public TextView show_message;
public ImageView profile_image;
private item_on_click_listener item_on_click_listener;
public ViewHolder(View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
profile_image = itemView.findViewById(R.id.profile_image);
}
public void setItem_on_click_listener(item_on_click_listener item_on_click_listener){
this.item_on_click_listener = item_on_click_listener;
}
#Override
public void onClick(View view) {
item_on_click_listener.onClick(view, getAdapterPosition(), false);
}
#Override
public boolean onLongClick(View view) {
item_on_click_listener.onClick(view, getAdapterPosition(), false);
return true;
}
}
#Override
public int getItemViewType(int position) {
i = position;
if(mChat.get(position).getSender() == "Sender Name"){
return MSG_TYPE_RIGHT;
}
else{
return MSG_TYPE_LEFT;
}
}
#Override
public void onAttachedToRecyclerView(#NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
recyclerView.refreshDrawableState();
}
}
Here is the main-activity class:
public class MainActivity extends AppCompatActivity {
Button sendBtn;
ArrayList<String> messagesList = new ArrayList<>();
HubConnection hubConnection;
EditText edt_text;
TextView txt_received;
MessageAdapter messageAdapter;
List<Chat> mChat;
RecyclerView recyclerView;
public void readMessages(String sender, String receiver, String message){
Chat chat = new Chat(sender, receiver, message);
mChat.add(chat);
messageAdapter = new MessageAdapter(MainActivity.this, mChat, "default");
recyclerView.setAdapter(messageAdapter);
messageAdapter.notifyItemRangeChanged(messageAdapter.getItemCount(), mChat.size());
}
#SuppressLint("WrongThread")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
mChat = new ArrayList<>();
messageAdapter = new MessageAdapter(MainActivity.this, mChat, "default");
recyclerView.setAdapter(messageAdapter);
sendBtn = findViewById(R.id.send_btn);
edt_text = findViewById(R.id.edt_text);
try {
hubConnection = HubConnectionBuilder.create("URL").build();
hubConnection.start();
AtomicReference<String> state = new AtomicReference<>("");
hubConnection.start().subscribe(() -> {
state.set("Connect");
},
error -> {
state.set("error");
});
hubConnection.on("SendMessage", (param1, param2, param3, param4) -> {
readMessages("Sender Name", "Receiver Name", "Message");
}, String.class, String.class, String.class, Integer.class);
}
catch (Exception e){
String exMessage = e.getMessage();
}
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
if(edt_text.getText().toString().length() > 0){
if(hubConnection.getConnectionState() == HubConnectionState.DISCONNECTED){
hubConnection.start();
}
hubConnection.send("Method Name", "param1", "param2", "param3", "param4");
hubConnection.on("ReceiveMessage", (param1, param2, param3 , param4) -> {
readMessages("Sender Name", "Receiver Name", "Message");
}, String.class, String.class, String.class, Integer.class);
}
else{
edt_text.setHint("Can not be empty");
}
}catch (Exception ex){
String message ;
message = ex.getMessage();
}
}
});
}
}
Can anyone help me, please?
notifyItemRangeChanged will work if you add/remove the data in same instance of Adapter or any other notify method for that matter. The problem here is you are creating a new Adapter every time inside your readMessages method.
Create adapter only once and notify it as needed .. Since you already created the messageAdapter inside onCreate you can use the same instance.
public void readMessages(String sender, String receiver, String message){
Chat chat = new Chat(sender, receiver, message);
mChat.add(chat);
messageAdapter.notifyItemRangeChanged(messageAdapter.getItemCount(), mChat.size());
}
Here in the given below code, I am trying to display in the image in recyclerview in the imageview after fetching it using picasso, it won't show error or app won't crash either but image won't be displayed, it either shows:
"I/Choreographer: Skipped 30 frames! The application may be doing too much work on its main thread."
Or
W/RecyclerView: No adapter attached; skipping layout
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
LayoutInflater inflater;
List<Lists> lst;
private ItemClickListsner mItemListener;
public Adapter(Context ctx, List<Lists> lst, ItemClickListsner itemClickListsner) {
this.inflater = LayoutInflater.from(ctx);
this.lst = lst;
this.mItemListener = itemClickListsner;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// final Lists temp = lst.get(position);
holder.id.setText(lst.get(position).getId());
holder.name.setText(lst.get(position).getName());
holder.prc.setText(lst.get(position).getPrc());
holder.add.setText(lst.get(position).getAddress());
holder.description.setText(lst.get(position).getDes());
holder.park.setText(lst.get(position).getGarage());
holder.net.setText(lst.get(position).getNet());
holder.email.setText(lst.get(position).getMail());
holder.number.setText(lst.get(position).getPnumber());
holder.post.setText(lst.get(position).getTle());
holder.date.setText(lst.get(position).getCrt());
Picasso.with(inflater.getContext())
.load(lst.get(position).getMimage())
.placeholder(R.drawable.bed)
.fit()
.into(holder.ImgView);
holder.itemView.setOnClickListener(view -> {
mItemListener.onItemClick(lst.get(position));
});
}
#Override
public int getItemCount() {
return lst.size();
}
public interface ItemClickListsner{
void onItemClick(Lists lst);
}
public void filterList(ArrayList<Lists> filteredList) {
lst = filteredList;
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView id, name, add, prc, description, park, net, post,email,number,date;
ImageView ImgView;
// CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.textViewRecy1);
name = itemView.findViewById(R.id.textViewRecy2);
prc = itemView.findViewById(R.id.textViewRecy3);
add = itemView.findViewById((R.id.textViewRecy4));
description = itemView.findViewById(R.id.textViewRecy5);
park = itemView.findViewById(R.id.textViewRecy6);
net = itemView.findViewById(R.id.textViewRecy7);
post = itemView.findViewById(R.id.textViewRecy8);
email = itemView.findViewById(R.id.textViewRecy9);
number = itemView.findViewById(R.id.textViewRecy10);
date = itemView.findViewById(R.id.textViewRecy11);
ImgView = itemView.findViewById(R.id.ImageRecy);
}
}
}
Activity Code
private void extractList() {
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
//Log.d("tags", "error: " + jsonObject);
Lists lists = new Lists();
lists.setName(jsonObject.getString("title").toString());
lists.setAddress(jsonObject.getString("location").toString());
lists.setPrc(jsonObject.getString("price").toString());
lists.setDes(jsonObject.getString("description").toString());
lists.setGarage(jsonObject.getString("parking").toString());
lists.setNet(jsonObject.getString("internet").toString());
lists.setMail(jsonObject.getString("email").toString());
lists.setPnumber(jsonObject.getString("phone_number").toString());
lists.setTle(jsonObject.getString("poster").toString());
lists.setCrt(jsonObject.getString("created").toString());
lists.setMimage(jsonObject.getString("photo1").toString());
String p = jsonObject.getString("photo1").toString();
Log.e("kk","msg"+p);
lst.add(lists);
} catch (JSONException e) {
e.printStackTrace();
}
}
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter = new Adapter(getApplicationContext(), lst, new Adapter.ItemClickListsner() {
#Override
public void onItemClick(Lists lst) {
// startActivity(new Intent(HomeActivity.this,roomsDesc.class));
Intent intent = new Intent(HomeActivity.this, roomsDesc.class);
intent.putExtra("title",lst.getName());
intent.putExtra("price",lst.getPrc());
intent.putExtra("location",lst.getAddress());
intent.putExtra("description",lst.getDes());
intent.putExtra("parking",lst.getGarage());
intent.putExtra("internet",lst.getNet());
intent.putExtra("email",lst.getMail());
intent.putExtra("phone_number",lst.getPnumber());
intent.putExtra("poster",lst.getTle());
intent.putExtra("created",lst.getCrt());
intent.putExtra("photo1",lst.getMimage());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
HomeActivity.this.startActivity(intent);
}
});
recyclerView.setAdapter(adapter);
}
I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.
My cart
This is what i need.
Total value need to be updated when one item removed.
I managed to remove the item and get the total value as json respose in adapter viewholder . don't know how to set the update the text in Fragment.
this is my cart fragment
Cart.java
public class Cart extends Fragment {
public Cart() {
// Required empty public constructor
}
Context context;
Activity activity;
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://192.168.0.106/slbros/index.php/get/cart?p_d_id=12&lan=en";
String Total_URL = "http://192.168.0.106/slbros/index.php/get/total?p_d_id=12";
String JSON_CDID = "cart_dtl_id";
String JSON_IMG_URL = "img_url";
String JSON_QTY = "qty";
String JSON_NAME = "name";
String JSON_UNIT = "unit";
String JSON_PRICE = "price";
String JSON_P_ID = "product_id";
JsonArrayRequest jsonArrayRequest;
RequestQueue requestQueue;
ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_cart, container, false);
TextView total_tv = (TextView)v.findViewById(R.id.total_payment_value);
//recycler view
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) v.findViewById(R.id.rv_cart_list);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar2);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Cart");
}
public void JSON_DATA_WEB_CALL() {
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(), "some error....", Toast.LENGTH_SHORT).show();
}
}
);
requestQueue = Volley.newRequestQueue(getContext());
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(60000, 0, 1));
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.setImg_url(json.getString(JSON_IMG_URL));
GetDataAdapter2.setName(json.getString(JSON_NAME));
GetDataAdapter2.setPrice(json.getInt(JSON_PRICE));
GetDataAdapter2.setProduct_id(json.getInt(JSON_P_ID));
GetDataAdapter2.setCart_dtl_id(json.getInt(JSON_CDID));
GetDataAdapter2.setProduct_qty(json.getInt(JSON_QTY));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapterCart(GetDataAdapter1, getContext());
recyclerView.setAdapter(recyclerViewadapter);
}}
this is my adapter
RecyclerViewAdapterCart.java
public class RecyclerViewAdapterCart extends RecyclerView.Adapter<RecyclerViewAdapterCart.ViewHolder> {
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
String baseURL = "http://192.168.0.106/slbros/index.php/";
Context context;
Activity activity;
List<GetDataAdapter> getDataAdapter;
ImageLoader imageLoader1;
public RecyclerViewAdapterCart(List<GetDataAdapter> getDataAdapter, Context context) {
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getDataAdapter1.getImg_url(),
ImageLoader.getImageListener(
Viewholder.product_image_view,//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.product_image_view.setImageUrl(getDataAdapter1.getImg_url(), imageLoader1);
Viewholder.product_name_TextView.setText(getDataAdapter1.getName()+" - "+String.valueOf(getDataAdapter1.getProduct_qty()));
Viewholder.product_price_qty_TextView.setText(getDataAdapter1.getPrice()+".00 Rs X "+String.valueOf(getDataAdapter1.getProduct_qty()));
Viewholder.product_t_price_TextView.setText(String.valueOf(getDataAdapter1.getProduct_qty()*getDataAdapter1.getPrice())+".00 Rs");
Viewholder.product_id_TextView.setText(String.valueOf(getDataAdapter1.getProduct_id()));
Viewholder.cart_dtl_id_TextView.setText(String.valueOf(getDataAdapter1.getCart_dtl_id()));
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public NetworkImageView product_image_view;
public TextView product_name_TextView;
public TextView product_price_qty_TextView;
public TextView product_t_price_TextView;
public TextView product_id_TextView;
public TextView cart_dtl_id_TextView;
public Button p_cancel_btn;
public ViewHolder(View itemView) {
super(itemView);
product_image_view = (NetworkImageView) itemView.findViewById(R.id.item_image1);
product_name_TextView = (TextView) itemView.findViewById(R.id.product_name);
product_price_qty_TextView = (TextView) itemView.findViewById(R.id.p_qty_price);
product_t_price_TextView = (TextView) itemView.findViewById(R.id.p_t__price);
product_id_TextView = (TextView) itemView.findViewById(R.id.product_id_tv);
cart_dtl_id_TextView = (TextView) itemView.findViewById(R.id.cart_dtl_id_tv);
p_cancel_btn = (Button)itemView.findViewById(R.id.p_cancel_btn);
// set item view
p_cancel_btn.setOnClickListener(this);
}
#Override
public void onClick(final View v) {
String str = product_name_TextView.getText().toString();
//Toast.makeText(v.getContext(), str, Toast.LENGTH_SHORT).show();
String cart_dtl_id = cart_dtl_id_TextView.getText().toString();
String url = baseURL + "delete/select?cart_dtl_id="+cart_dtl_id;
jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//progressBar.setVisibility(View.GONE);
Toast.makeText(v.getContext(), "response -- " + response, Toast.LENGTH_LONG).show();
// here, I have to change the total TextView in Fragment
// Total_TextView.setText("1000rs")
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(v.getContext(), "error", Toast.LENGTH_LONG).show();
}
}
);
requestQueue = Volley.newRequestQueue(v.getContext());
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(60000,0,1));
requestQueue.add(jsonArrayRequest);
getDataAdapter.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
notifyItemRangeChanged(getAdapterPosition(),getDataAdapter.size());
}
}}
Thanks in Advance
add to ReyclerView.
private ItemsChangedListener itemsChangedListener;
public interface ItemsChangedListener {
void onItemsChanged(int sum);
}
public void setItemsChangedListener(ItemsChangedListener listener) {
this.itemsChangedListener = listener;
}
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//progressBar.setVisibility(View.GONE);
// Calc here the Value if you can.
if(listener != null) listener.onItemsChanged(sum);
}
Fragment
public class Cart extends Fragment implements ItemsChangedListener
recyclerView.setItemsChangedListener(this);
#override
public void onItemsChanged(int sum) {
//Update TextView
}
I am trying to search for items with a SearchView but I do not know why I can not find the possible way, can you help me?
FragGridCampos.java
public class FragGridCampos extends Fragment implements SearchView.OnQueryTextListener{
//Creating a List of jornadas
private List<Estadisticas> listJornadas;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private List<Estadisticas> mCountryModel;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate( R.layout.campos_list_todos, null);
setHasOptionsMenu(true);
recyclerView = (RecyclerView) view.findViewById( R.id.recyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
recyclerView.setLayoutManager(layoutManager);
TextView miTexto = (TextView)view.findViewById( R.id.mi_texto);
miTexto.setText("CAMPOS");
//miTexto.setTextColor(color.RED);
listJornadas = new ArrayList<>();
getData();
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new DecoracionLineaDivisoria(getActivity()));
/*ImageButton fabButton = (ImageButton) view.findViewById(R.id.fab);
fabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//startActivity(new Intent(getActivity(), MainActivity2.class));
Toast.makeText(getActivity(),"Proximamente",Toast.LENGTH_SHORT).show();
}
});*/
return view;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_buscar, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
}
//This method will get data from the web api
private void getData(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(getActivity(),"Cargando datos", "Por favor espere...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigAmaters.CAMPOS,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
Estadisticas campo = new Estadisticas();
JSONObject json = null;
try {
json = array.getJSONObject(i);
campo.setNombre_campo(json.getString("nombre_campo"));
campo.setPoblacion(json.getString("poblacion"));
campo.setEquipo(json.getString("equipo"));
campo.setTelefono(json.getString("telefono"));
campo.setGeo(json.getString("geo"));
campo.setUrl(json.getString("url"));
campo.setEmail(json.getString("email"));
campo.setEscudo(json.getString("escudo"));
} catch (JSONException e) {
e.printStackTrace();
}
listJornadas.add(campo);
}
//Finally initializing our adapter
adapter = new Campos_Adapter(listJornadas, getActivity());
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private LayoutInflater getMenuInflater() {
return null;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<Estadisticas> filteredModelList = filter(mCountryModel, newText);
adapter.setFilter(filteredModelList);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private List<Estadisticas> filter(List<Estadisticas> models, String query) {
query = query.toLowerCase();final List<Estadisticas> filteredModelList = new ArrayList<>();
for (Estadisticas model : models) {
final String text = model.getPoblacion().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
Campos_Adapter.java
private ImageLoader imageLoader;
private Context context;
List<Estadisticas> estadisticas;
public Campos_Adapter(List<Estadisticas> estadisticas, Context context) {
super();
this.estadisticas = estadisticas;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from( parent.getContext() ).inflate( R.layout.campos_row, parent, false );
ViewHolder viewHolder = new ViewHolder( v );
return viewHolder;
}
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.root.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(context, "this is my Toast message!!! =)",
//Toast.LENGTH_LONG).show();
//Toast.makeText(context, estadisticas.get(position).getNombrePlato(), Toast.LENGTH_SHORT).show();
Intent intent= new Intent(context, DetailCampos.class);
intent.putExtra("Poblacion", estadisticas.get(position).getPoblacion());
intent.putExtra("Nombre_campo", estadisticas.get(position).getNombre_campo());
intent.putExtra("Nombre", estadisticas.get(position).getEquipo());
intent.putExtra("Telefono", estadisticas.get(position).getTelefono());
intent.putExtra("Geo", estadisticas.get(position).getGeo());
intent.putExtra("Email", estadisticas.get(position).getEmail());
intent.putExtra("Url", estadisticas.get(position).getUrl());
intent.putExtra("Imagen", estadisticas.get(position).getEscudo());
context.startActivity(intent);
Estadisticas estadisticas1 = estadisticas.get(getAdapterPosition());
}
private int getAdapterPosition() {
return 0;
}
} );
Estadisticas campos = estadisticas.get( position );
imageLoader = DecoracionLineaDivisoria.CustomVolleyRequest.getInstance(context ).getImageLoader();
imageLoader.get(campos.getEscudo(), ImageLoader.getImageListener(holder.escudo_local, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert ) );
holder.textViewEquipo_Local.setText( campos.getEquipo() );
holder.textViewPoblacion.setText( campos.getPoblacion() );
//holder.escudo_local.setImageUrl( campos.getImagenPlato(), imageLoader );
}
#Override
public int getItemCount() {
return estadisticas.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView escudo_local;
public TextView textViewEquipo_Local;
public TextView textViewPoblacion;
public View root;
public ViewHolder(View itemView) {
super( itemView );
root = itemView;
escudo_local = (ImageView) itemView.findViewById( R.id.tv_esc_local );
textViewEquipo_Local = (TextView) itemView.findViewById( R.id.tv_ek_local );
textViewPoblacion = (TextView) itemView.findViewById( R.id.tv_poblacion );
}
}
public void setFilter(List<Estadisticas> countryModels) {
estadisticas = new ArrayList<>();
estadisticas.addAll(countryModels);
notifyDataSetChanged();
}
}
In line *adapter.setFilter(filteredModelList);
setFilter is in red.
My error is *Error:(182, 16) error: cannot find symbol method setFilter(List)
1. Instead of declaring Adapter as:
private RecyclerView.Adapter adapter;
Use:
private Campos_Adapter adapter;
2. In addition, initialize adapter from onCreateView() and use adapter.notifyDataSetChanged() from parseData() method.
Update onCreateView() and parseData() as below:
//Creating a List of jornadas
private List<Estadisticas> listJornadas;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Campos_Adapter adapter;
private List<Estadisticas> mCountryModel;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...........
...................
listJornadas = new ArrayList<Estadisticas>();
adapter = new Campos_Adapter(listJornadas, getActivity());
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new DecoracionLineaDivisoria(getActivity()));
getData();
.........
.............
return view;
}
//This method will parse json data
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
Estadisticas campo = new Estadisticas();
JSONObject json = null;
try {
json = array.getJSONObject(i);
campo.setNombre_campo(json.getString("nombre_campo"));
campo.setPoblacion(json.getString("poblacion"));
campo.setEquipo(json.getString("equipo"));
campo.setTelefono(json.getString("telefono"));
campo.setGeo(json.getString("geo"));
campo.setUrl(json.getString("url"));
campo.setEmail(json.getString("email"));
campo.setEscudo(json.getString("escudo"));
} catch (JSONException e) {
e.printStackTrace();
}
listJornadas.add(campo);
adapter.notifyDataSetChanged();
}
}
UPDATE:
java.lang.NullPointerException: Attempt to invoke interface method
'java.util.Iterator java.util.List.iterator()' on a null object
reference at
com.ramon.campos.Campos.FragGridCampos.filter(FragGridCampos.java:185)
Your mCountryModel is null. You have not initialized it. In onQueryTextChange() try below code:
#Override
public boolean onQueryTextChange(String newText) {
mCountryModel.addAll(listJornadas);
final List<Estadisticas> filteredModelList = filter(mCountryModel, newText);
adapter.setFilter(filteredModelList);
return true;
}
The solution:
FragGridCampos.java
public class FragGridCampos extends Fragment implements SearchView.OnQueryTextListener{
//Creating a List of jornadas
private List<Estadisticas> listJornadas;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Campos_Adapter adapter;
private List<Estadisticas> mCountryModel;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate( R.layout.campos_list_todos, null);
setHasOptionsMenu(true);
recyclerView = (RecyclerView) view.findViewById( R.id.recyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
recyclerView.setLayoutManager(layoutManager);
TextView miTexto = (TextView)view.findViewById( R.id.mi_texto);
miTexto.setText("CAMPOS");
//miTexto.setTextColor(color.RED);
listJornadas = new ArrayList<Estadisticas>();
adapter = new Campos_Adapter(listJornadas, getActivity());
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new DecoracionLineaDivisoria(getActivity()));
getData();
/*ImageButton fabButton = (ImageButton) view.findViewById(R.id.fab);
fabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//startActivity(new Intent(getActivity(), MainActivity2.class));
Toast.makeText(getActivity(),"Proximamente",Toast.LENGTH_SHORT).show();
}
});*/
return view;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_buscar, menu);
final MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
}
//This method will get data from the web api
private void getData(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(getActivity(),"Cargando datos", "Por favor espere...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigAmaters.CAMPOS,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
Estadisticas campo = new Estadisticas();
JSONObject json = null;
try {
json = array.getJSONObject(i);
campo.setNombre_campo(json.getString("nombre_campo"));
campo.setPoblacion(json.getString("poblacion"));
campo.setEquipo(json.getString("equipo"));
campo.setTelefono(json.getString("telefono"));
campo.setGeo(json.getString("geo"));
campo.setUrl(json.getString("url"));
campo.setEmail(json.getString("email"));
campo.setEscudo(json.getString("escudo"));
} catch (JSONException e) {
e.printStackTrace();
}
listJornadas.add(campo);
adapter.notifyDataSetChanged();
}
}
#Override
public boolean onQueryTextChange(String newText) {
final List<Estadisticas> filteredModelList = filter(listJornadas, newText);
adapter.setFilter(filteredModelList);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private List<Estadisticas> filter(List<Estadisticas> models, String query) {
query = query.toLowerCase();final List<Estadisticas> filteredModelList = new ArrayList<>();
for (Estadisticas model : models) {
final String poblacion = model.getPoblacion().toLowerCase();
final String equipo = model.getEquipo().toLowerCase();
if (poblacion.contains(query)) {
filteredModelList.add(model);
}
else if (equipo.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
Campos_Adapter.java
public class Campos_Adapter extends RecyclerView.Adapter<Campos_Adapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
List<Estadisticas> estadisticas;
public Campos_Adapter(List<Estadisticas> estadisticas, Context context) {
super();
this.estadisticas = estadisticas;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from( parent.getContext() ).inflate( R.layout.campos_row, parent, false );
ViewHolder viewHolder = new ViewHolder( v );
return viewHolder;
}
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.root.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(context, "this is my Toast message!!! =)",
//Toast.LENGTH_LONG).show();
//Toast.makeText(context, estadisticas.get(position).getNombrePlato(), Toast.LENGTH_SHORT).show();
Intent intent= new Intent(context, DetailCampos.class);
intent.putExtra("Poblacion", estadisticas.get(position).getPoblacion());
intent.putExtra("Nombre_campo", estadisticas.get(position).getNombre_campo());
intent.putExtra("Nombre", estadisticas.get(position).getEquipo());
intent.putExtra("Telefono", estadisticas.get(position).getTelefono());
intent.putExtra("Geo", estadisticas.get(position).getGeo());
intent.putExtra("Email", estadisticas.get(position).getEmail());
intent.putExtra("Url", estadisticas.get(position).getUrl());
intent.putExtra("Imagen", estadisticas.get(position).getEscudo());
context.startActivity(intent);
Estadisticas estadisticas1 = estadisticas.get(getAdapterPosition());
}
private int getAdapterPosition() {
return 0;
}
} );
Estadisticas campos = estadisticas.get( position );
imageLoader = DecoracionLineaDivisoria.CustomVolleyRequest.getInstance(context ).getImageLoader();
imageLoader.get(campos.getEscudo(), ImageLoader.getImageListener(holder.escudo_local, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert ) );
holder.textViewEquipo_Local.setText( campos.getEquipo() );
holder.textViewPoblacion.setText( campos.getPoblacion() );
}
#Override
public int getItemCount() {
return estadisticas.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView escudo_local;
public TextView textViewEquipo_Local;
public TextView textViewPoblacion;
public View root;
public ViewHolder(View itemView) {
super( itemView );
root = itemView;
escudo_local = (ImageView) itemView.findViewById( R.id.tv_esc_local );
textViewEquipo_Local = (TextView) itemView.findViewById( R.id.tv_ek_local );
textViewPoblacion = (TextView) itemView.findViewById( R.id.tv_poblacion );
}
}
public void setFilter(List<Estadisticas> countryModels) {
estadisticas = new ArrayList<>();
estadisticas.addAll(countryModels);
notifyDataSetChanged();
}
}