Rating Bar gets 0 in recycler view - android

In my app I have a recycler view that holds a name and address of a restaurant and I just tried to add a rating bar to it and I get all the data from SQL database and I use volley for connecting to it, every thing works fine and I can even send a rating for a restaurant but when I try to get the data I get 0
and I checked the REST API and Json, when I set the rating with a final value without database in my Recycler adapter class It works but when I try to set the data in my MainActivity and geting it in my on bindview holder it gets 0 please help
MainActivty
public void sendRequest(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, request_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
restaurants.clear();
for (int i = 0; i < response.length(); i++) {
Restaurant restaurant = new Restaurant();
try {
JSONObject jsonObject = response.getJSONObject(i);
restaurant.setId(jsonObject.getInt("restaurant_id"));
restaurant.setName(jsonObject.getString("restaurant_name"));
restaurant.setAddress(jsonObject.getString("restaurant_address"));
restaurant.setImage(jsonObject.getInt("restaurant_image_type"));
restaurant.setHasNote(jsonObject.getBoolean("restaurant_has_note"));
restaurant.setRating((float) jsonObject.getInt("restaurant_rating"));
swipeRefreshLayout.setRefreshing(false);
} catch (JSONException e) {
swipeRefreshLayout.setRefreshing(false);
Log.i("VolleyGetError",e.toString());
e.printStackTrace();
}
restaurants.add(restaurant);
adapter.notifyDataSetChanged();
shimmerContainer.stopShimmerAnimation();
shimmerContainer.setVisibility(View.GONE);
}
fastfoodRecyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley Error:", String.valueOf(error));
}
});
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(jsonArrayRequest);
}
My POJO class
public Restaurant() {
}
public Restaurant(String name, String address,int type){
this.name = name;
this.address = address;
this.type = type;
}
public Restaurant(int id, String name, String address,int type){
this.id = id;
this.name = name;
this.address = address;
this.type = type;
}
public Restaurant(int id, String name, String address, int type,int image,int count) {
this.id = id;
this.name = name;
this.address = address;
this.type = type;
this.image = image;
this.count = count;
}
public Restaurant(int id, String name, String address, int type,int image,int count,float rating) {
this.id = id;
this.name = name;
this.address = address;
this.type = type;
this.image = image;
this.count = count;
this.rating = rating;
}
public float getRating() {
return rating;
}
public int getCount() {
return count;
}
public void setRating(float rating) {
this.rating = rating;
}
public void setCount (int count) {this.count = count;}
public int getId() { return id;}
public void setId (int id) { this.id = id;}
public String getName() {
return name;
}
public void setName(String name) { this.name = name;}
public boolean isHasNote(){
return hasNote;
}
public void setHasNote(boolean hasNote){
this.hasNote = hasNote;
}
public String getAddress() { return address;}
public void setAddress(String address) { this.address = address;}
public void setType(int type) {this.type = type;}
public int getType() {return type;}
public int getImage() {return image;}
public void setImage(int image) {this.image = image;}
}
my Recycler Adapter class
TextView listviewName,listviewAddress;
ImageView icon,noteIcon,deleteicon;
RelativeLayout viewBackground, viewForeground;
RatingBar ratingBar;
MyViewHolder(View view){
super(view);
ratingBar = view.findViewById(R.id.rating_bar);
listviewName = view.findViewById(R.id.listview_name);
listviewAddress = view.findViewById(R.id.listview_address);
icon = view.findViewById(R.id.type_ic);
noteIcon = view.findViewById(R.id.note_icon);
deleteicon = view.findViewById(R.id.delete_icon);
deleteicon.setVisibility(View.GONE);
viewBackground = view.findViewById(R.id.view_background);
viewForeground = view.findViewById(R.id.view_foreground);
view.setOnCreateContextMenuListener(this);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onRestaurantSelected(restaurantListFiltered.get(getAdapterPosition()));
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.add(0, 1, 0, "Edit");
menu.add(0, 2, 1, "Remove");
menu.add(0, 3, 2, "Add Note");
menu.add(0, 4, 3, "All Notes");
}
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
Animation animation = AnimationUtils.loadAnimation(context, R.anim.fadein);
itemView.startAnimation(animation);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
setPosition(holder.getAdapterPosition());
return false;
}
});
Restaurant restaurant = restaurantList.get(position);
holder.listviewName.setText(restaurant.getName());
holder.listviewAddress.setText(restaurant.getAddress());
holder.ratingBar.setRating(restaurant.getRating());
switch (restaurant.getImage()) {
case RestaurantContract.EntryRestaurants.RESTAURANT_TYPE_DELIVERY:
holder.icon.setImageResource(R.drawable.phoneorderr);
break;
case RestaurantContract.EntryRestaurants.RESTAURANT_TYPE_SITDOWN:
holder.icon.setImageResource(R.drawable.sitdownn);
break;
case RestaurantContract.EntryRestaurants.RESTAURANT_TYPE_TAKEAWAY:
holder.icon.setImageResource(R.drawable.takeaway);
break;
}
holder.noteIcon.setImageResource(R.drawable.notepadicon);
if(restaurant.isHasNote()) {
holder.noteIcon.setVisibility(View.VISIBLE);
}else {
holder.noteIcon.setVisibility(View.INVISIBLE);
}
}
My json
{
"restaurant_id": "97",
"restaurant_name": "tt",
"restaurant_address": "rr",
"restaurant_type": "0",
"restaurant_has_note": "0",
"restaurant_image_type": "2",
"restaurant_rating": "3"
}
]

Firstly, you've your POJO class as Restaurant. Add below value to your rating field
public Restaurant(){
public float rating = 0.0f;
}
Secondly, you'll need to listen your rating bar changes on your MyViewHolder like below:
ratingBar = (RatingBar) view.findViewById(R.id.rating_bar);
ratingBar .setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
restaurants.get(getPosition()).rating = ratingBar.getRating();
}
});
I see you've already implemented an arraylist with the name of restaurantList, i've still mentioned the implementation below for reference:
Then in your Adapter you'll have to implement an arraylist to fetch the data for your ratingBar
static List<Restaurant> restaurants= new ArrayList<>(); //restaurantList in your
Initiate it in your constructor.
this.restaurants = restaurants;//restaurantList in your case
Then in your onBindViewHolder
List<String> restro= new ArrayList<String>();
for(int i=0;i<restaurants.size();i++){
restro.add(String.valueOf(restaurants.rating));//restaurantList in your case
}
Hope that helps.

Related

how to fetch a images from database using retrofit 2

Hi I am new to Retrofit framework for Android. I could get JSON responses from REST services using it but I don't know how to fetch a image using retrofit2. I am trying to fetch the image in recyclerview from the database
Code is Here:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
Intent intent = getIntent();
parent = intent.getStringExtra("Parent");
child = intent.getStringExtra("Child");
Toast.makeText(this, parent+child, Toast.LENGTH_SHORT).show();
//init firebase
//load menu
recycler_menu =(RecyclerView)findViewById(R.id.recycler_view);
apiInterface =
ApiClient.getRetrofit().create(ApiInterface.class);
recycler_menu.setLayoutManager(new GridLayoutManager(this, 2));
recycler_menu.setHasFixedSize(true);
mUploads = new ArrayList<>();
loadMenu();
}
private void loadMenu(){
Toast.makeText(Product.this, "Hello",
Toast.LENGTH_SHORT).show();
Call<Upload> call = apiInterface.performProduct(parent,child);
call.enqueue(new Callback<Upload>() {
#Override
public void onResponse(Call<Upload> call, Response<Upload>
response) {
Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
mAdapter = new ImageAdapter(Product.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onFailure(Call<Upload> call, Throwable t) {
}
});
}}
ImageAdapter.java .
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getImgName());
holder.textViewPrice.setText(uploadCurrent.getPrice());
Picasso.get()
.load(uploadCurrent.getImgUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.imageView);
//holder.collection.setText(uploadCurrent.getmRadioGroup());
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener {
public TextView textViewName;
public TextView textViewPrice;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.menu_name);
textViewPrice = itemView.findViewById(R.id.menu_price);
imageView = itemView.findViewById(R.id.menu_price);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
}
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
Upload.class
public class Upload {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#SerializedName("id")
private String id;
#SerializedName("image")
private String imgName;
#SerializedName("imgUrl")
private String imgUrl;
#SerializedName("price")
private String price;
#SerializedName("description")
private String Description;
#SerializedName("response")
private String Response;
public String getResponse(){
return Response;
}
public Upload() {
}
public Upload(String id,String imgName, String imgUrl, String price, String Description) {
this.id = id;
this.imgName = imgName;
this.imgUrl = imgUrl;
this.price = price;
this.Description = Description;
}
public String getImgName() {
return imgName;
}
public void setImgName(String imgName) {
this.imgName = imgName;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getDescription() {
return Description;
}
public void setDescription(String Description) {
this.Description = Description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
PHP File:
<?php include ("conn.php");
$type = $_GET["parent"];
$ttype = $_GET["child"];
$sth = $conn->prepare("SELECT * from product where type='$type' &&
s_type='$ttype'");
$sth->execute();
While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
$name = $data['name'];
$id = $data['id'];
$des = $data['description'];
$price = $data['price'];
$image = $data['image'];
$status = "ok";
echo
json_encode(array("response"=>$status,
"img"=>$image,"name"=>$name,
"id"=>$id,"description"=>$des,"price"=>$price));
}?>
this code does nothing a blank screen appers
You are sending blank ArrayList to Adapter
look here In onCreate() you assign mUploads = new ArrayList<>();
then you just pass mUploads to mAdapter = new ImageAdapter(Product.this, mUploads);
chnage code from
#Override
public void onResponse(Call<Upload> call, Response<Upload>
response) {
Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
mAdapter = new ImageAdapter(Product.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
}
to ,
#Override
public void onResponse(Call<Upload> call, Response<Upload>
response) {
Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
mUploads=responese.body(); //# add this line
mAdapter = new ImageAdapter(Product.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
}
From your endpoint I got the following response
{"response":"ok","img":"greypant.jpg","name":"GreyPant","id":"1","description":"A very fine pant with great finishing.","price":"1500"}
you can try making the following edits to your PHP file to get the full path to the image file(s).
<?php
include ("conn.php");
$type = $_GET["parent"];
$ttype = $_GET["child"];
$sth = $conn->prepare("SELECT * from product where type='$type' &&
s_type='$ttype'");
$sth->execute();
While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
$name = $data['name'];
$id = $data['id'];
$des = $data['description'];
$price = $data['price'];
$image = $data['image'];
$status = "ok";
echo json_encode(array("response"=>$status,
"img"=> "http://yourdomain.com/{$image}",
"name"=>$name,
"id"=>$id,
"description"=>$des,
"price"=>$price));
}
?>
replace http://yourdomain.com/ with the full path to the directory where your image is saved. Good luck!

Find Out How to Get Data in Firebase's Android Studio (There are many hierarchies)

I'm implementing my small app. Today,
I'm having trouble getting data from my Firebase.
Here is my Firebase structure:
This is modal Request:
public class Request {
// private String phone, name, address, total, status;
private String phone, name, address, status;
private int total;
private List<Order> foods;
public Request() {
}
public Request(String phone, String name, String address, int total, List<Order> foods) {
this.phone = phone;
this.name = name;
this.address = address;
this.total = total;
this.foods = foods;
this.status = "0"; //Default 0. 0: place, 1: shipping, 2: shipped
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Order> getFoods() {
return foods;
}
public void setFoods(List<Order> foods) {
this.foods = foods;
}
}
I obtained the Order data by going to "PhoneNumber" and getting the
"ID Order" data as follows:
private FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_status);
//Firebase:
FirebaseDatabase database = FirebaseDatabase.getInstance();
requests = database.getReference("Requests");
//init:
recyclerView = (RecyclerView) findViewById(R.id.recycler_orderview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
loadOrders(Common.currentUser.getPhone());
//Common.currentUser.getPhone() This is PhoneNumber current
}
private void loadOrders(final String phone) {
adapter = new FirebaseRecyclerAdapter<Request, OrderViewHolder>(
Request.class,
R.layout.order_item,
OrderViewHolder.class,
requests.child(phone) // I have access to "PhoneNumber"
) {
#Override
protected void populateViewHolder(OrderViewHolder viewHolder, Request model, int position) {
viewHolder.txtOrderId.setText(adapter.getRef(position).getKey());
viewHolder.txtOrderStatus.setText(convertCodeToStatus(model.getStatus()));
viewHolder.txtOrderPhone.setText(model.getPhone());
viewHolder.txtOrderAddress.setText(model.getAddress());
viewHolder.txtOrderTotal.setText(String.valueOf(model.getTotal()));
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
// Get CategoryID and send Activity Foods List:
Intent moveToOrderDetails = new Intent(OrderStatusActivity.this, OrderDetailsActivity.class);
moveToOrderDetails.putExtra("KeyOrder", adapter.getRef(position).getKey());
startActivity(moveToOrderDetails);
}
});
}
};
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
And this is my Apdapter:
public class OrderViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener {
public TextView txtOrderId, txtOrderStatus, txtOrderPhone, txtOrderAddress, txtOrderTotal;
private ItemClickListener itemClickListener;
public OrderViewHolder(View itemView) {
super(itemView);
txtOrderId = (TextView) itemView.findViewById(R.id.order_id);
txtOrderStatus = (TextView) itemView.findViewById(R.id.order_status);
txtOrderPhone = (TextView) itemView.findViewById(R.id.order_phone);
txtOrderAddress = (TextView) itemView.findViewById(R.id.order_address);
txtOrderTotal = (TextView) itemView.findViewById(R.id.order_total);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
#Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
contextMenu.setHeaderTitle("Select the action");
contextMenu.add(0, 0, getAdapterPosition(), Common.UPDATE);
contextMenu.add(0, 1, getAdapterPosition(), Common.DELETE);
}
}
And now I'm having trouble figuring out how to get the data of all
orders without having to go to "Number Phone". I tried to think and
perform but failed.
This is image demo about an order:

display json data letest record as per user id

i wont to display the list of chats of clients.the data is come from json,
the last message of chat is display on chat.but it displays all message of all clients in list.like
here is my ListMessage.class activity
public class ListMessage extends AppCompatActivity implements View.OnClickListener {
ImageButton btnFooter_Home, btnFooter_Message, btnFooter_Notification, btnFooter_More;
EditText textUser;
List<Msg_data> msgList;
ListView lv;
String uri = "http://staging.talentslist.com/api/user/23/chat";
LinearLayout linear_Home, linear_Message, linear_Notification, linear_More;
GlobalClass myGlog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_message);
myGlog = new GlobalClass(getApplicationContext());
setFooter();
lv = (ListView) findViewById(R.id.listView);
textUser = (EditText) findViewById(R.id.textUser);
// textUser.isFocused()
boolean inConnected = myGlog.isNetworkConnected();
if (inConnected) {
requestData(uri);
}
}
public void requestData(String uri) {
StringRequest request = new StringRequest(uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
msgList = MsgJSONParser.parseData(response);
MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);
lv.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ListMessage.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
}
MsgAdapter.java class
public class MsgAdapter extends BaseAdapter{
private Context context;
private List<Msg_data> nList;
private LayoutInflater inflater = null;
private LruCache<Integer, Bitmap> imageCache;
private RequestQueue queue;
String isread;
public MsgAdapter(Context context, List<Msg_data> list) {
this.context = context;
this.nList = list;
inflater = LayoutInflater.from(context);
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
imageCache = new LruCache<>(cacheSize);
queue = Volley.newRequestQueue(context);
}
public class ViewHolder {
TextView __isread;
TextView _username;
TextView _detais;
TextView _time;
ImageView _image;
}
#Override
public int getCount() {
return nList.size();
}
#Override
public Object getItem(int position) {
return nList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
final Msg_data msg = nList.get(position);
final ViewHolder holder;
isread = msg.getIs_read();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_notification, null);
if (isread.equals("0")) {
convertView.setBackgroundColor(Color.parseColor("#009999"));
}
holder = new ViewHolder();
holder._username = (TextView) convertView.findViewById(R.id.tvtitle);
holder._detais = (TextView) convertView.findViewById(R.id.tvdesc);
holder.__isread = (TextView) convertView.findViewById(R.id.tvplateform);
holder._time = (TextView) convertView.findViewById(R.id.createdTime);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder._username.setText(msg.getUser_name().toString());
holder._detais.setText(msg.getMessage().toString());
holder._time.setText(msg.getCreated_at().toString());
// holder.__isread.setText(notifi.getIs_read().toString());
holder._image = (ImageView) convertView.findViewById(R.id.gameImage);
Glide.with(context)
.load(msg.getImage_link().toString()) // Set image url
.diskCacheStrategy(DiskCacheStrategy.ALL) // Cache for image
.into(holder._image);
return convertView;
}
}
Msg_data.java class
public class Msg_data {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getIs_read() {
return is_read;
}
public void setIs_read(String is_read) {
this.is_read = is_read;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public Msg_data() {
}
public Msg_data(int id) {
this.id = id;
}
}
MsgJSONParser.java class
public class MsgJSONParser {
static List<Msg_data> notiList;
public static List<Msg_data> parseData(String content) {
JSONArray noti_arry = null;
Msg_data noti = null;
try {
JSONObject jsonObject = new JSONObject(content);
noti_arry = jsonObject.getJSONArray("data");
notiList = new ArrayList<>();
for (int i = 0; i < noti_arry.length(); i++) {
JSONObject obj = noti_arry.getJSONObject(i);
//JSONObject obj = noti_arry.getJSONObject(i);
noti = new Msg_data();
noti.setId(obj.getInt("id"));
noti.setMessage(obj.getString("message"));
noti.setUser_name(obj.getString("user_name"));
noti.setFrom(obj.getString("from"));
noti.setTo(obj.getString("to"));
noti.setCreated_at(obj.getString("created_at"));
noti.setImage_link(obj.getString("image_link"));
noti.setIs_read(obj.getString("is_read"));
notiList.add(noti);
}
return notiList;
} catch (JSONException ex) {
ex.printStackTrace();
return null;
}
}
}
please give me some idea what to do and how to do
i guess, you should replace
msgList = MsgJSONParser.parseData(response);
MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);
with
msgList = MsgJSONParser.parseData(response);
ArrayList<Msg_data> userList=new ArrayList();
for (int i=0;i<msgList.size();i++){
if (!userList.contains(msgList.get(i)))
userList.add(msgList.get(i));
else {
int index=userList.indexOf(msgList.get(i));
if (userList.get(index).compareTo(msgList.get(i))>0)
userList.add(msgList.get(i));
}
}
MsgAdapter adapter = new MsgAdapter(ListMessage.this, userList);`
and implement Comparable and override equals method in your Msg_data class
public class Msg_data implements Comparable {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getIs_read() {
return is_read;
}
public void setIs_read(String is_read) {
this.is_read = is_read;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public Msg_data() {
}
public Msg_data(int id) {
this.id = id;
}
#Override
public boolean equals(Object obj) {
try
{
return (this.getUser_id().equals(( (Msg_data)obj).getUser_id()));
}
catch(NullPointerException e){
return false;
}
}
#Override
public int compareTo(#NonNull Object o) {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("your pattern here");
try {
Date date=simpleDateFormat.parse(created_at);
Date dateOtherObject=simpleDateFormat.parse(((Msg_data)o).getCreated_at());
return date.compareTo(dateOtherObject);
}
catch (ParseException e){
return -1;
}
}
something like this:) Dont forget replace simple date format in compare method

How to display json data in Recyclerview?

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.

i want to sorting my listview by user Android

i have 2 classes to show some data in list view
but i want make option for users to sort this list view
this is adapter class
public class CustomListViewAdapter extends BaseAdapter {
private Activity activity;
private Book[] data;
private static LayoutInflater inflater=null;
public CustomListViewAdapter(Activity a, Book list[]) {
activity = a;
data=list;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getBookId(int position){
return data[position].getId();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView row_id =(TextView)vi.findViewById(R.id.row_id);
TextView name=(TextView)vi.findViewById(R.id.title);
TextView descp = (TextView) vi.findViewById(R.id.artist);
TextView note_type = (TextView) vi.findViewById(R.id.row_note_type);
ImageView image=(ImageView)vi.findViewById(R.id.image);
row_id.setText(String.valueOf(data[position].getId()));
name.setText(data[position].getTitle());
descp.setText(data[position].getContent());
//row_id.setText(data[position].getId());
note_type.setText(data[position].getType());
//image.setImageResource(R.drawable.subway);
if(data[position].getImage().toString().equals("Facebook")){
image.setImageResource(R.drawable.facebook);
}else if(data[position].getImage().toString().equals("skype")){
image.setImageResource(R.drawable.skype);
}else if(data[position].getImage().toString().equals("Subway")){
image.setImageResource(R.drawable.subway);
}else if(data[position].getImage().toString().equals("Book")){
image.setImageResource(R.drawable.book);
}
return vi;
}
}
and this is book class
public class Book {
private int id;
private String title;
private String content; // this is content of table
private String image; // choosing images
private String type; // type of table ( note or task)
private int archived; // Archive table (true or false)
private int check; // make overline when finish (true or false)
private int protect; // protect the table with password (true or false)
private String password; // password of table if it was protected
private String date_added;
public Book() {}
public Book(String title, String content, String image, String type, int archived,
int check, int protect, String password) {
this.title = title;
this.content = content;
this.image = image;
this.type = type;
this.archived = archived;
this.check = check;
this.protect = protect;
this.password = password;
}
// ---- setter
public void setId(int id){
this.id = id;
}
public void setTitle(String title){
this.title = title;
}
public void setContent(String content){
this.content = content;
}
public void setImage(String image){
this.image = image;
}
public void setType(String type){
this.type = type;
}
public void setArchived(int archived){
this.archived = archived;
}
public void setCheck(int check){
this.check = check;
}
public void setProtect(int protect){
this.protect = protect;
}
public void setPassword(String password){
this.password = password;
}
public void setDate_added(String date_added){
this.date_added = date_added;
}
// --- getter ---
public int getId(){
return id;
}
public String getTitle(){
return title;
}
public String getContent(){
return content;
}
public String getImage(){
return image;
}
public String getType(){
return type;
}
public int getArchived(){
return archived;
}
public int getCheck(){
return check;
}
public int getProtect(){
return protect;
}
public String getPassword(){
return password;
}
public String getDate_added() {
return date_added;
}
public String toString(){
return "Book >> id:"+id+" | title:"+title+" | author:";
}
}
and this is method for showing the data in list view but BookTable is class of connect and get data from sqlite
public void list_Books() {
BookTable bt = new BookTable(getActivity());
adapter = new CustomListViewAdapter(getActivity(), bt.getAllBooks());
list.setAdapter(adapter);
list.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View arg1,int pos, long id) {
selected = adapter.getBookId(pos);
row_type = (TextView) arg1.findViewById(R.id.row_note_type);
return false;
}
});
registerForContextMenu(list);
}
i want to know how can i sorting this data by objects of my Book class
please i want speed answer
One approach of sorting is for your object Book to implement Comparable interface:
public class Book implements Comparable<Book>{
private int id;
#Override
public int compareTo(Book another) {
if(this.id >= another.id)
return 1;
return -1;
}
}
If you want to sort after you query the data from database you can just call the Collections sort() method:
Collections.sort(list);
If you dont want to implement Comparable interface, you can just create a Comparator and call the following method of Collections:
Collections.sort(list, new Comparator<Book>() {
#Override
public int compare(Book lhs, Book rhs) {
if(lhs.id >= rhs.id)
return 1;
return -1;
}
});
To reverse the order (as frequently it is requiredfor sorting):
Collections.sort(list, Collections.reverseOrder());
After you sort the list dont forget to notify the adapter to refresh the view:
adapter.notifyDataSetChanged();

Categories

Resources