I am creating an order app for part of a project I am working on. Basically, on one activity the user can view a list of all the items pulled from a database as a ListView. They also have a EditText field where they can enter the quantity they would like to order below each item.
I would like to have a submit button at the bottom of the screen which will then post the details of all the items ordered (i.e their item id) and the quantity being ordered however I am unsure how to do this.
Here is my current code:
public class OrderItems extends AppCompatActivity {
String menuID;
private TextView menuTitle;
ListView listView;
List<OrderItemList> listOrderItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_items);
menuTitle = findViewById(R.id.tvOrderMenuTitle);
Intent intent = getIntent();
String title = intent.getStringExtra("title");
menuID = intent.getStringExtra("id");
menuTitle.setText(title);
listView = findViewById(R.id.list_order_items);
listOrderItems = new ArrayList<>();
displayItems();
}
private void displayItems(){
String url = "hidden";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("menuitems");
for (int i = 0; i < array.length(); i++) {
final JSONObject menuObj = array.getJSONObject(i);
OrderItemList o = new OrderItemList(menuObj.getString("menu_item_name"),
menuObj.getString("item_type"), menuObj.getInt("menu_item_price"), menuObj.getInt("menu_item_qty"));
listOrderItems.add(o);
}
OrderItemAdapter adapter = new OrderItemAdapter(listOrderItems, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(OrderItems.this, "Oops! " +error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("menuid", menuID);
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
}
Displaying the items works fine although I am unable to type into the EditText box the quantity of the items to order, once I type it and then go to the next box, the previous value disappears.
The model class looks like this:
public class OrderItemList {
String Name, Type;
int Price, Qty;
public OrderItemList(String name, String type, int price, int qty) {
Name = name;
Type = type;
Price = price;
Qty = qty;
}
public String getName() {
return Name;
}
public int getQty() {
return Qty;
}
public String getType() {
return Type;
}
public int getPrice() {
return Price;
}
}
and the adapter:
public class OrderItemAdapter extends ArrayAdapter <OrderItemList>{
private List<OrderItemList> orderItemList1;
private Context context;
public OrderItemAdapter(List<OrderItemList> M, Context C){
super(C, R.layout.listorder, M);
this.orderItemList1 = M;
this.context = C;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.listorder,null,true);
TextView menuItemName = view.findViewById(R.id.tvItemName);
TextView menuItemPrice = view.findViewById(R.id.tvItemPrice);
TextView menuItemType = view.findViewById(R.id.tvItemType);
TextView menuItemQty = view.findViewById(R.id.tvItemQty);
OrderItemList orderItemList = orderItemList1.get(position);
menuItemName.setText(orderItemList.getName());
menuItemQty.setText("Available quantity: " +orderItemList.getQty());
menuItemPrice.setText("£" +orderItemList.getPrice());
if(position>0){
OrderItemList prevOrderItemList = orderItemList1.get(position-1);
if(!orderItemList.getType().equals(prevOrderItemList.getType())){
menuItemType.setText(orderItemList.getType());
}
} else {
menuItemType.setText(orderItemList.getType());
}
return view;
}
}
Any help/adivce would be greatly appreciated!
Related
this is my adapter code
I tried more method, but it's still not working
I don't know where has problem
public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CommentViewHolder> {
private Context mContext;
private List<CommentModel> mData;
RequestManager glide;
private LayoutInflater mInflater = null;
private OnItemClickListener mOnItemClickListener = null;
public CommentAdapter(List<CommentModel> mData, Context mContext){
super();
this.mContext = mContext;
this.mData = mData;
this.glide = Glide.with(mContext);
}
#NonNull
#Override
public CommentViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//View row = LayoutInflater.from(mContext).inflate(R.layout.row_comment,parent,false);
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_comment, parent, false);
CommentViewHolder commentViewHolder = new CommentViewHolder(v);
return commentViewHolder;
}
#Override
public void onBindViewHolder(#NonNull CommentViewHolder holder, final int position) {
final CommentModel commentModel = mData.get(position);
//glide.load(mData.get(position).getUserPhoto()).into(holder.img_user);
Glide.with(mContext).load(mData.get(position).getUserPhoto()).into(holder.img_user);
holder.tv_name.setText(mData.get(position).getUsername());
holder.tv_content.setText(mData.get(position).getComment());
holder.tv_date.setText(mData.get(position).getTime());
}
#Override
public int getItemCount() {
return mData==null ? 0 : mData.size();
//return mData.size();
}
public void addTheCommentData(CommentModel commentModel){
if(commentModel!=null){
mData.add(commentModel);
this.notifyDataSetChanged();
}else {
throw new IllegalArgumentException("No Data!");
}
}
public interface OnItemClickListener {
void onClick(View parent, int position);
}
public class CommentViewHolder extends RecyclerView.ViewHolder{
ImageView img_user;
TextView tv_name,tv_content,tv_date;
public CommentViewHolder(View itemView) {
super(itemView);
img_user = itemView.findViewById(R.id.comment_user_img);
tv_name = itemView.findViewById(R.id.comment_username);
tv_content = itemView.findViewById(R.id.comment_comment);
tv_date = itemView.findViewById(R.id.comment_date);
}
}
}
This is my comment code,
When I type the info and submit, it's will writing my server, but the notifyDataSetChanged is no working.
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the newFeedModel object
CommentModel newCommentModel = new CommentModel();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
String TAG_CommentID = "CommentID";
String TAG_CommentFID = "CommentFID";
String TAG_CommentUID = "CommentUID";
String TAG_Comment = "Comment";
String TAG_PostUserPhoto = "PostUserPhoto";
String TAG_Username = "Username";
String TAG_Time = "Time";
//String TAG_CommentPhoto = "CommentPhoto";
//Adding data to the newFeedModel object
//Log.d("photo", json.getString(TAG_PostUserPhoto));
newCommentModel.setCommentID(json.getString(TAG_CommentID));
newCommentModel.setFeedID(json.getString(TAG_CommentFID));
newCommentModel.setUserID(json.getString(TAG_CommentUID));
newCommentModel.setComment(json.getString(TAG_Comment));
newCommentModel.setUserPhoto(json.getString(TAG_PostUserPhoto));
newCommentModel.setUsername(json.getString(TAG_Username));
newCommentModel.setTime(json.getString(TAG_Time));
//newCommentModel.setTimestamp(json.getString(TAG_CommentPhoto));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the newFeedModel object to the list
//listCommentModel.add(newCommentModel);
adapter.addTheCommentData(newCommentModel);
}
//Notifying the adapter that data has been added or changed
this.adapter.notifyDataSetChanged();
//getNewDate();
}
But it cannot be working, I don't know what's happen.
Who can told me where need to modify?
I need to leave activity then go back will display.
First Add ArrayList of CommentModel,
Then Add Your Adapter an pass List via constructor of adapter
CommentAdapter adapter;
ArrayList<CommentModel> list;
Inside Parsing
list = new ArrayList<CommentModel>();
list.add(newCommentModel)
adapter = new CommentAdapter(list,this);
So, I need to add under code in CommentModel.java
public class CommentModel {
private String CommentID;
private String FeedID;
private String UserID;
private String Comment;
private String UserPhoto;
private String Username;
private String Time;
CommentAdapter adapter;
ArrayList<CommentModel> list;
public CommentModel(String nickName, String content, String img) {
this.Username = nickName;
this.Comment = content;
this.UserPhoto = img;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
then, this code in activicy
editTextComment = findViewById(R.id.post_detail_comment);
feedid = findViewById(R.id.feedid);
recyclerView = (RecyclerView) findViewById(R.id.rv_comment);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
list = new ArrayList<CommentModel>();
list.add(newCommentModel)
adapter = new CommentAdapter(list,this);
is this right?
I want to show inner json array in Recyclerview.
I was getting all the data in logcat.
But my problem is how to write code in adapter class for inner array items.
My problem is like this question
How to get data from nested json array android
I have similar json array.
I want to pass arraylist to Adapter.
This is my modal
public class OuterModal {
String menuId;
String menuName;
private List<InnerModal> innerItem;
public String getMenuId() {
return menuId;
}
public void setMenuId(String menuId) {
this.menuId = menuId;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public List<InnerModal> getInnerItem() {
return innerItem;
}
public void setInnerItem(List<InnerModal> innerItem) {
this.innerItem = innerItem;
}
}
This is my another modal
public class InnerModal {
String vendor_item_id;
String vendor_id;
String vendor_item_name;
String vendor_item_image;
String vendor_item_price;
String vendor_item_category;
String vendor_item_description;
String vendor_item_status;
public String getVendor_item_id() {
return vendor_item_id;
}
public void setVendor_item_id(String vendor_item_id) {
this.vendor_item_id = vendor_item_id;
}
public String getVendor_id() {
return vendor_id;
}
public void setVendor_id(String vendor_id) {
this.vendor_id = vendor_id;
}
public String getVendor_item_name() {
return vendor_item_name;
}
public void setVendor_item_name(String vendor_item_name) {
this.vendor_item_name = vendor_item_name;
}
public String getVendor_item_image() {
return vendor_item_image;
}
public void setVendor_item_image(String vendor_item_image) {
this.vendor_item_image = vendor_item_image;
}
public String getVendor_item_price() {
return vendor_item_price;
}
public void setVendor_item_price(String vendor_item_price) {
this.vendor_item_price = vendor_item_price;
}
public String getVendor_item_category() {
return vendor_item_category;
}
public void setVendor_item_category(String vendor_item_category) {
this.vendor_item_category = vendor_item_category;
}
public String getVendor_item_description() {
return vendor_item_description;
}
public void setVendor_item_description(String vendor_item_description) {
this.vendor_item_description = vendor_item_description;
}
public String getVendor_item_status() {
return vendor_item_status;
}
public void setVendor_item_status(String vendor_item_status) {
this.vendor_item_status = vendor_item_status;
}
}
This is JSON Responce
StringRequest stringRequest = new StringRequest(Request.Method.GET,
mainUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("menu");
List<OuterModal> outerModalList=new ArrayList<>();
OuterModal outerModal=new OuterModal();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
String menu_id = json.getString("menu_id");
String menu_name = json.getString("menu_name");
outerModal.setMenuId(menu_id);
outerModal.setMenuName(menu_name);
JSONArray productsListArray = json.getJSONArray("Products List");
for (int j = 0; j < productsListArray.length(); j++) {
// Log.d("myDraaa", "list responce:" + productsListArray);
JSONObject productsListjson = productsListArray.getJSONObject(j);
InnerModal innerModal=new InnerModal();
List<InnerModal> innerModalList=new ArrayList<>();
String vendor_item_id = productsListjson.getString("vendor_item_id");
String vendor_id = productsListjson.getString("vendor_id");
String vendor_item_name = productsListjson.getString("vendor_item_name");
String vendor_item_image = productsListjson.getString("vendor_item_image");
String vendor_item_status = productsListjson.getString("vendor_item_status");
String quantity = productsListjson.getString("quantity");
innerModal.setVendor_id(vendor_id);
innerModal.setVendor_item_id(vendor_item_id);
innerModal.setVendor_item_category("");
innerModal.setVendor_item_description("");
innerModal.setVendor_item_image(vendor_item_image);
innerModal.setVendor_item_name(vendor_item_name);
innerModal.setVendor_item_status(vendor_item_status);
innerModal.setVendor_item_price(quantity);
outerModal.getInnerItem().add(innerModal);
}
outerModalList.add(outerModal);
}
public class SecondAdapter extends RecyclerView.Adapter<SecondAdapter.SecondVH> {
List<OuterModal> arrayList;
Context context;
public SecondAdapter(List<OuterModal> arrayList, Context context) {
this.arrayList = arrayList;
this.context = context;
}
#NonNull
#Override
public SecondVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.my_custom_style, null, false);
return new SecondVH(v);
}
#Override
public void onBindViewHolder(#NonNull SecondVH holder, final int position) {
OuterModal outerModal=arrayList.get(position);
holder.title.setText(outerModal.getMenuName());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class SecondVH extends RecyclerView.ViewHolder {
TextView title;
TextView items;
ConstraintLayout constraintLayout;
TextView itemName, itemPrice, itemDescription;
public SecondVH(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.bestSellers);
items = itemView.findViewById(R.id.myCustItemName);
constraintLayout = itemView.findViewById(R.id.csL);
itemPrice = itemView.findViewById(R.id.itemPrice);
itemDescription = itemView.findViewById(R.id.itemDesc);
}
}
}
Thanks in advance.
Please help me.
I have received a json data from rest api. This data contains id, title, body, an array of images "appImages" and a teaserImage. Now I deserialize the json in controller class. I have creted two adapters. First adpter is used for recyclerview. This recycler view is showing the title and and teasetImage. this portion working. If user click on item it redirect to detail activity, where he can see teaserImage as cover image, and the body as description. Now this layout I oroganised this way, at fisrt the ImageView for cover Image, TextView for Description. And below description I have created a recyclerView to show the array of images. The CoverImage and description of detail cativity is working well. For recyclerview I have created another Adpater, this adapter is used to show all the images based on the title of news. But I stuch to show those images in recyclerview. I have explained in deatil in my code.
My controller class
public class NewsController {
private static final String TAG = NewsController.class.getSimpleName();
private UserCallbackListener mListener;
private NewsRestApiManager mApiManager;
private AppImage appImages;
public NewsController(UserCallbackListener listener) {
mListener = listener;
mApiManager = new NewsRestApiManager();
}
public void startFetching(){
mApiManager.getNewsApi().getNews(new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d(TAG, "JSON :: " + s);
try {
JSONArray array = new JSONArray(s);
for(int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
NewsModel news = new NewsModel();
news.setTitle( jsonObject.optString( "title") );
news.setBody( jsonObject.optString( "body" ) );
ArrayList<AppImage> list = new ArrayList();
JSONArray imageArray =jsonObject.getJSONArray("appImages");
if (imageArray.length() > 1) {
for(int j=0; j<imageArray.length();j++){
appImages = new AppImage();
appImages.setSrc(new JSONArray( s ).getJSONObject( i ).getJSONArray( "appImages" ).getJSONObject( j ).getString( "src" ));
list.add(appImages);
}
}
news.setAppImages( list );
TeaserImageSmall coverImage=new TeaserImageSmall();
coverImage.setSrc( new JSONArray( s ).getJSONObject( i ).getJSONObject( "teaserImageSmall" ).getString( "src" ));
news.setTeaserImageSmall(coverImage);
mListener.onFetchProgressNews(news);
}
} catch (JSONException e) {
mListener.onFetchFailed();
}
mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error :: " + error.getMessage());
mListener.onFetchComplete();
}
});
}
public interface UserCallbackListener{
void onFetchStart();
void onFetchProgressNews(NewsModel news);
void onFetchProgressNews(List<NewsModel> userList);
void onFetchComplete();
void onFetchFailed();
}
My adapter class for News Recyclerview. This is perfect now.
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsHolder>
........
public void addNews(NewsModel news) {
Log.d(TAG,news.getTeaserImageSmall().getSrc());
mNews.add(news);
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(NewsHolder holder, int position) {
final NewsModel currentNews = mNews.get(position);
Picasso.with(holder.itemView.getContext());
Picasso.with(holder.itemView.getContext()).load(currentNews.getTeaserImageSmall().getSrc()).into( holder.newsImage );
holder.newsHeadline.setText(currentNews.getTitle());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i=new Intent(context,DetailNews.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("src",currentNews.getTeaserImageSmall().getSrc());
i.putExtra("title",currentNews.getTitle());
i.putExtra("body",currentNews.getBody());
context.startActivity(i);
}
});
Now Another Adapter for Array of images which will show in detail activity of news page.
Edited Adapter Class
public class NewsImageAdapter extends RecyclerView.Adapter<NewsImageAdapter.ImageHolder> {
public static String TAG = NewsImageAdapter.class.getSimpleName();
private Context context;
private List<AppImage> appImageList;
DetailNews detailNews = new DetailNews ();
public NewsImageAdapter(List<AppImage> imageObject,Context context) {
this.context = context;
this.appImageList = imageObject;
}
public void addImage(AppImage appImage) {
Log.d(TAG,appImage.getSrc());
appImageList.add(appImage);
notifyDataSetChanged();
}
#Override
public ImageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.newsdetail_image_row,parent,false);
return new ImageHolder(view);
}
#Override
public void onBindViewHolder(ImageHolder holder, int position) {
final AppImage currentImage=appImageList.get(position);
//getting error for current news,
detailNews .navigate(context, appImageList, currentNews.getTeaserImageSmall().getSrc(), currentNews.getTitle(),currentNews.getBody());
Picasso.with(holder.itemView.getContext()).load(currentImage.getSrc()).into( holder.images);
}
#Override
public int getItemCount() {
return imageObject.size();
}
public class ImageHolder extends RecyclerView.ViewHolder {
public ImageView images;
public ImageHolder(View itemView) {
super(itemView);
images= itemView.findViewById(R.id.news_image);
}
}
}
Detail activity of news where I am shoing coverImage and description at this moment. But I also want to show the list of images below the description. I would like to how can I implement that.
Edited Detail Activity
public class DetailNews extends AppCompatActivity{
public class DetailNews extends AppCompatActivity{
private RecyclerView recyclerView;
private NewsImageAdapter adapter;
private List<AppImage> imageList= new ArrayList<>();
private NewsController mController;
private CardView cardview;
private ImageView _coverImage;
private TextView _newsHeading;
private TextView _description;
private TextView _newsDate;
private static List<AppImage> appImageList,mAppImageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_detail);
//newsObject=getAllImageList();
// setting up views and stuff
setUpUIViews();
Intent intent = getIntent();
//RECEIVE DATA
Log.e("_coverImage",""+_coverImage);
String coverImage = intent.getStringExtra ("src");
String heading=intent.getExtras().getString("title");
//String newsDate=intent.getExtras().getString("date");
String description=intent.getExtras().getString("body");
//BIND DATA
Picasso.with(this).load(coverImage ).into(_coverImage);
_newsHeading.setText(heading);
// _newsDate.setText(newsDate);
_description.setText(description);
Linkify.addLinks( _description,Linkify.WEB_URLS );
}
private void setUpUIViews() {
_coverImage=(ImageView)findViewById(R.id.news_cover);
_newsHeading=(TextView)findViewById(R.id.heading);
_description=(TextView)findViewById(R.id.news_description);
_newsDate=(TextView)findViewById(R.id.date);
cardview=(CardView) findViewById(R.id.cardView);
recyclerView = (RecyclerView)findViewById(R.id.image_list);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(DetailNews.this);
recyclerView.setLayoutManager(layoutManager);
adapter = new NewsImageAdapter(imageList,getApplicationContext() );
recyclerView.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
public void navigate(Context activity, List<AppImage> appImageList, String src, String title, String body) {
mAppImageList = appImageList;
Intent intent = new Intent(activity, DetailNews .class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("src",src);
intent .putExtra("title",title);
intent .putExtra("body",body);
activity.startActivity(intent);
try {
if (activity instanceof NewasPage) { //Error for news
((NewsPage) activity).finish();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
My Mdel Class is
public class NewsModel {
#Expose
private String _id;
#Expose
private String body;
#Expose
private String title;
#Expose
private List<AppImage> appImages;
public List<AppImage> getAppImages() {
return appImages;
}
public void setAppImages(List<AppImage> appImages) {
this.appImages = appImages;
}
AppImage Model Class
public class AppImage {
#Expose
private String _id;
#Expose
private String alt;
#Expose
private String src;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getAlt() {
return alt;
}
public void setAlt(String alt) {
this.alt = alt;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
}
In DetailNews Activity, add a method
private static List<AppImage> appImageList mAppImageList;
public void navigate(Context activity, List<AppImage> appImageList,String src,String title,String body) {
mAppImageList = appImageList;
Intent intent = new Intent(activity, DetailNews .class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("src",src);
intent .putExtra("title",title);
intent .putExtra("body",body);
activity.startActivity(intent);
try {
if (activity instanceof FirstActivity) {
((FirstActivity) activity).finish();
}
} catch (Exception e) {
e.printStackTrace();
}
}
And in the adapter do as
DetailNews detailNews = new DetailNews ();
detailNews .navigate(context, appImageList, currentNews.getTeaserImageSmall().getSrc(), currentNews.getTitle(),currentNews.getBody());
I want to sort an ArrayList of HashMaps
ArrayList < HashMap < String,Object>>
in the following class:
public class NotificationFragment extends ListFragment {
private static final String TAG = "NotificationFragment";
private DatabaseReference mDatabaseReference;
private ProgressBar mProgressBar;
String[] from = {"TITLE","BODY","TIME"};
int[] to = {R.id.single_notification_row_title,
R.id.single_notification_row_body,
R.id.single_notification_row_time};
ArrayList<HashMap<String,Object>> data;
SimpleAdapter adapter;
public NotificationFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_notification, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Set Activity title
getActivity().setTitle(R.string.Notifications);
mDatabaseReference = FirebaseDatabase.getInstance().getReference()
.child("Notification").child("Android");
Query query = mDatabaseReference.orderByChild("title");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
getNewData((Map<String,Object>)dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(), R.string.Something_went_wrong_retry, Toast.LENGTH_SHORT).show();
}
});
}
private void cancelNotification(Activity activity, int notifyId) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) activity.getSystemService(ns);
nMgr.cancel(notifyId);
}
private void getNewData (Map<String,Object> mapDatabase){
mProgressBar = (ProgressBar)getActivity().findViewById(R.id.progressBarNotifications);
data = new ArrayList<>();
try{
//Iterate through each notification
for(Map.Entry<String,Object> entry : mapDatabase.entrySet()){
Log.e(TAG, "ForEach entered");
Map singleNotification = (Map)entry.getValue();
//Fill the list
String title = (String) singleNotification.get("title");
String body = (String) singleNotification.get("body");
String time = (String) singleNotification.get("time");
String timeLong = (String) singleNotification.get("timeStamp");
HashMap<String,Object> map = new HashMap<>();
map.put("TITLE", title);
map.put("BODY", body);
map.put("TIME", time);
map.put("timeLong", timeLong);
data.add(map);
Log.d(TAG,"data.add(map)");
Log.d(TAG,"data.size = " + data.size());
}
for(HashMap<String, Object> myMap: data) {
for(Map.Entry<String, Object> mapEntry: myMap.entrySet()) {
String key = mapEntry.getKey();
String value = (String) mapEntry.getValue();
if(key.equals("timeLong")){
Log.d(TAG,"timeLong = " + value);
//?????????HOW TO SORT by LONG VALUE ??????????
}
}
}
//Adapter
adapter = new SimpleAdapter
(getActivity(),data,R.layout.single_notification_row ,from,to);
setListAdapter(adapter);
Log.d(TAG,"setListAdapter(adapter)");
}catch (NullPointerException e){
Toast.makeText(getActivity(), R.string.No_Notifications, Toast.LENGTH_SHORT).show();
}
if(mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.GONE);
}
cancelNotification(getActivity(), 0);
}
#Override
public void onStart() {
super.onStart();
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getActivity(), "HI", Toast.LENGTH_SHORT).show();
}
});
}
}
I get the following sorting order:
Screenshot
Please note that I have one single Long item (called "timeLong") in every ArrayList item.
Thank you in advance,
Gaetano
,I suggest you to create a class which contains 4 properties :
String title;
String body;
String time;
long timeLong;
Lets say the name of the class is Instance. When you get the data, create an instance of this class and set the properties of this instance instead of having 4 string values.
Change your ArrayList to this ArrayList<Instance> myList = ArrayList();
Create a class
public class SortingClass implements Comparator<Instance>
{
public int compare(Instance left, Instance right){
return left.timeLong < right.timeLong ? 1 : -1;
}
And for sorting
Collections.sort(myList,new SortingClass())
I want to display data from Mysql database in Recyclerview i use this codes but i get white page nothing show i don't know where error please help me to find error please explain your answer because i'm new in android this my codes
Mainactivity.java
RequestQueue requestQueue;
ArrayList<listitem_gib> rewayaList = new ArrayList<>();
private RecyclerView recyclerView;
ProgressBar progressBar;
LinearLayout progress_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cardview);
TextView progress_txt = (TextView) findViewById(R.id.progress_txt);
progress_layout = (LinearLayout) findViewById(R.id.progress_layout);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
String url = "http://grassyhat.com/android/arabic.php";
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
progress_layout.setVisibility(View.GONE);
try {
JSONArray jsonArray = response.getJSONArray("all");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String img = respons.getString("img");
String url = respons.getString("url");
String num = respons.getString("num");
String size = respons.getString("size");
rewayaList.add(new listitem_gib(id, name, img, url, num, size));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
//Just your list of objects, in your case the list that comes from the db
CardAdapter adapter = new CardAdapter(rewayaList, this);
//RecyclerView needs a layout manager in order to display data so here we create one
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
//Here we set the layout manager and the adapter to the listview
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
Adapter
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
private List<listitem_gib> rewayaList;
Context context;
public CardAdapter(List<listitem_gib> rewayaList, Context context) {
super();
this.rewayaList = rewayaList;
this.context = context;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout, parent, false);
CardViewHolder viewHolder = new CardViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(CardViewHolder holder, int position) {
//Here you bind your views with the data from each object from the list
listitem_gib rewaya = rewayaList.get(position);
holder.rewaya_name.setText(rewaya.name);
holder.writer_name.setText(rewaya.num);
}
#Override
public int getItemCount() {
return rewayaList.size();
}
public class CardViewHolder extends RecyclerView.ViewHolder {
public ImageView Image;
public TextView rewaya_name, writer_name;
public CardViewHolder(View itemView) {
super(itemView);
Image = (ImageView) itemView.findViewById(R.id.image);
rewaya_name = (TextView) itemView.findViewById(R.id.Main_Text);
writer_name = (TextView) itemView.findViewById(R.id.Second_Text);
}
}}
ListItem
public class listitem_gib {
public String id;
public String name;
public String img;
public String url;
public String num;
public String size;
public listitem_gib(String id, String name, String img, String url, String num, String size) {
this.id = id;
this.name = name;
this.img = img;
this.url = url;
this.num = num;
this.size = size;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}}
it is hard to look to your code in figure out the error
in this cases you have to break down you code and test every part alone
first check that the response is coming form the server properly by print the response via LOG or toast then check the parsing part when you have arrayLst
then populate the data to the recycler view
After
rewayaList.add(new listitem_gib(id, name, img, url, num, size));
Add
adapter.notifyDataSetChanged();
For detailed explanation visit Official Documentation for the function notifyDataSetChanged. It's just a few sentences so don't be scared that it might be a lengthy documentation.