what's the Wrong
this code for chat application .. messages not shown and ProgressDialog still in the screen
Adapter class
public class chatadaptor extends RecyclerView.Adapter<chatadaptor.MyViewHolder>{
private Context mContext;
private List<Message> messageList;
public chatadaptor(Context mContext, List<Message> messageList) {
this.mContext = mContext;
this.messageList = messageList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView tv_time , tv_message_content;
RadioButton statusradiobutton ;
LinearLayout Rsenttext ,Rresecivedtext;
ImageView img_msg;
RelativeLayout Rsentpic ,Rresecivedp ;
public MyViewHolder(View view) {
super(view);
tv_time = (TextView) view.findViewById(R.id.tv_time);
tv_message_content = (TextView) view.findViewById(R.id.tv_message_content);
Rsenttext = (LinearLayout)view.findViewById(R.id.Rsenttext);
Rresecivedtext = (LinearLayout)view.findViewById(R.id.Rresecivedtext);
Rsentpic = (RelativeLayout)view.findViewById(R.id.Rsentpic);
Rresecivedp = (RelativeLayout)view.findViewById(R.id.Rresecivedp);
img_msg = (ImageView)view.findViewById(R.id.img_msg);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.chatting,parent,false);
MyViewHolder holder = new MyViewHolder(row);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final Message message = messageList.get(position);
holder.Rresecivedtext.setVisibility(View.VISIBLE);
holder.tv_message_content.setText(message.getContent());
Toast.makeText(mContext,message.getDegree() , Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return messageList.size();
}
}
Xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:id="#+id/Rresecivedtext"
android:orientation="vertical">
<TextView
android:id="#+id/tv_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:layout_marginTop="2dp"
android:gravity="start"
android:paddingEnd="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/app_name"
android:textColor="#color/colorPrimaryDark"
android:textSize="11sp" />
<FrameLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_username"
android:layout_gravity="start"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/received_message">
<TextView
android:id="#+id/tv_message_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="3dp"
android:gravity="center"
android:minWidth="60dp"
android:text=" مرحبا "
android:textColor="#color/album_title" />
</FrameLayout>
<TextView
android:id="#+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#id/container"
android:layout_alignRight="#id/container"
android:layout_below="#+id/container"
android:layout_marginBottom="4dp"
android:layout_marginTop="1dp"
android:gravity="end"
android:paddingLeft="10dp"
android:text="12:20 AM"
android:textColor="#color/colorPrimary"
android:textSize="11sp" />
</RelativeLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/Rsenttext"
android:visibility="v"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tv_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:layout_marginTop="2dp"
android:gravity="end"
android:paddingRight="10dp"
android:text="12:20 AM"
android:textSize="11sp" />
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:background="#drawable/sent_message">
<TextView
android:id="#+id/tv_message_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="2dp"
android:gravity="center"
android:minWidth="60dp"
android:text=" message text "
android:textColor="#color/white" />
</FrameLayout>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
And Activity
public void getMessages(){
progress=new ProgressDialog(this);
progress.setMessage(getResources().getString(R.string.wait));
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.setCancelable(true);
progress.show();
final Thread t = new Thread() {
#Override
public void run() {
String ADD_TOKEN_URL = "http://XXXXXXXXX/api/Chat.php";
StringRequest request = new StringRequest(Request.Method.POST, ADD_TOKEN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("1000")) {
Toast.makeText(userchats.this, "user error", Toast.LENGTH_SHORT).show();
progress.dismiss();
}else if (response.trim().equals("1111")){
Toast.makeText(userchats.this, "sending error", Toast.LENGTH_SHORT).show();
progress.dismiss();}
else {
response = response.substring(response.indexOf('\n')+1);
try {
String encodedstring = URLEncoder.encode(response, "ISO-8859-1");
response = URLDecoder.decode(encodedstring, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
try {
List<Message> messageList = new ArrayList<>();
Message message;
JSONObject object = new JSONObject(response);
JSONArray apparray = object.getJSONArray("chat");
for (int i = 0; i < apparray.length(); i++) {
JSONObject currentobject = apparray.getJSONObject(i);
String type = currentobject.getString("type");
String content = currentobject.getString("content");
String timestamp = currentobject.getString("timestamp");
String degree = currentobject.getString("degree");
SharedPreferences pref = getSharedPreferences("MyAccount", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
String Uid = pref.getString("Uid", null); // getting String
message = new Message( Uid, type, content, timestamp, degree);
messageList.add(message);
chatadaptor adapter = new chatadaptor(userchats.this , messageList);
recyclerChat.setAdapter(adapter);
}
// progress.dismiss();
} catch (JSONException e) {
e.printStackTrace();
} }
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(userchats.this, "error in sending message", Toast.LENGTH_SHORT).show(); progress.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
SharedPreferences pref = getSharedPreferences("MyAccount", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
String Uid = pref.getString("Uid", null); // getting String
params.put("action","view");
params.put("userid",Uid);
//params.put("type",lpasss);
// params.put("content",lpasss);
// params.put("timestamp",lpasss);
return params;
}
};
Volley.newRequestQueue(getBaseContext()).add(request);
}
};
t.start();
}
data come from serve and converted to JSONObject enter code here correctly
what's the Wrong
this code for chat application .. messages not shown and ProgressDialog still in the screen
just add following lines because you did not add layout manager for your recyclerview
recyclerChat.setLayoutManager(new LinearLayoutManager(this));
hope this works for you..
public class ServicesListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context con;
AtmHolder pvh1;
List<serviceListData> serviceslist;
public ServicesListAdapter(List<serviceListData> serviceslist, Context con) {
this.serviceslist = serviceslist;
this.con = con;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
RecyclerView.ViewHolder viewHolder = null;
if (position == 0) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.services_list_item_style, viewGroup, false);
viewHolder = new AtmHolder(v);
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof AtmHolder) {
pvh1 = (AtmHolder) holder;
pvh1.tv_service.setText(serviceslist.get(position).getName());
Glide.with(con)
.load("image url")
.placeholder(R.drawable.internet)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(pvh1.iv_service);
}
}
public int getItemViewType(int position) {
int a = 0;
return a;
}
#Override
public int getItemCount() {
return serviceslist.size();
}
public static class AtmHolder extends RecyclerView.ViewHolder {
ImageView iv_service;
TextView tv_service;
AtmHolder(View itemView) {
super(itemView);
iv_service = (ImageView) itemView.findViewById(R.id.iv_service);
tv_service = (TextView) itemView.findViewById(R.id.tv_service);
}
}
}
Related
I am retrieving Data from MySQL Database in Android and I am using Recyclerview .I test php file and it is working fine but nothing shows in the activity. I checked every thing and it seems fine, I don't know what is the problem ?
Waiting Activity :
<android.support.v7.widget.RecyclerView
android:id="#+id/recylcerView"
android:layout_width="1dp"
android:layout_height="1dp"
tools:layout_editor_absoluteX="745dp"
tools:layout_editor_absoluteY="51dp" />
</RelativeLayout>
list_layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/imageView"
android:layout_width="120dp"
android:layout_height="90dp"
android:padding="4dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:text=" Waiting Time :"
android:textColor="#000000"
android:textStyle="bold"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"/>
<TextView
android:id="#+id/textViewTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/imageView"
android:text="00"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/textViewRating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewTime"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/imageView"
android:background="#color/colorPrimary"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="Bus Number : "
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small.Inverse"
android:textStyle="bold" />
<TextView
android:id="#+id/textViewBusNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewRating"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/imageView"
android:text="255"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large" />
</RelativeLayout>
</LinearLayout>
WaitingActivity :
public class WaitingActivity extends AppCompatActivity {
private static final String URL_PRODUCTS = "http://192.168.1.2/Android/v1/test1.php";
List<Product> productList;
RecyclerView recyclerView;
ProductsAdapter adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waiting);
recyclerView = (RecyclerView) findViewById(R.id.recylcerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void loadProducts() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for (int i = 0; i < products.length(); i++) {
JSONObject productObject = products.getJSONObject(i);
int Temp_dt = productObject.getInt("Temp_dt");
int BusNumber =productObject.getInt("BusNumber");
Product product = new Product(Temp_dt, BusNumber);
productList.add(product);
}
adapter = new ProductsAdapter(WaitingActivity.this, productList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(WaitingActivity.this, error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
Product class :
public class Product {
private int Temp_dt;
private int BusNumber;
public Product(int Temp_dt, int BusNumber) {
this.Temp_dt = Temp_dt;
this.BusNumber = BusNumber ;
}
public int getWaitingTime() {
return Temp_dt;
}
public int getBusNumber() {
return BusNumber ;
}
}
ProductAdapter :
public class ProductsAdapter extends
RecyclerView.Adapter<ProductsAdapter.ProductViewHolder> {
private Context mCtx;
private List<Product> productList;
public ProductsAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.list_layout, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
Product product = productList.get(position);
holder.textViewTime.setText(String.valueOf(product.getWaitingTime()));
holder.textViewBusNumber.setText(String.valueOf(product.getBusNumber()));
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView textViewTime;
TextView textViewBusNumber;
public ProductViewHolder(View itemView) {
super(itemView);
textViewTime = itemView.findViewById(R.id.textViewTime);
textViewBusNumber = itemView.findViewById(R.id.textViewBusNumber);
}
}
}
I expect to show temp_dt and waiting time from php file but the actual output is nothing just empty activity.
I am wanting to display orders on a screen which I retrieve from a database. Each order has various items on it, and the screen will show the details of various orders and their items.
For example:
Order 1
Item1
Item2
Item3
Order2
Item4
Item5
,etc.
I am able to return this data with no issues, however I was wondering how to put a border around each order (as opposed to each item which is easy to do).
This is what the return looks like now (apologies as it does not show everything I wanted in this image). Basically I want a border around each specific order, so all the items in order 1 I want in a border, and then all the items in order 2 I want in a border.
The code is outline below and any help would be greatly appreciated:
This is the activity which displays the orders:
public class ChefScreen extends AppCompatActivity {
ListView listView;
List<ChefOrderList> listOrders;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chef_screen);
listView = findViewById(R.id.list_chef_orders);
listOrders = new ArrayList<>();
displayOrders();
}
private void displayOrders(){
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("orders");
for (int i = 0; i < array.length(); i++) {
final JSONObject orderObj = array.getJSONObject(i);
ChefOrderList c = new ChefOrderList(orderObj.getString("menu_item_name"), orderObj.getString("item_type"), orderObj.getString("order_date_time"),
orderObj.getInt("quantity_ordered"), orderObj.getInt("order_id"));
listOrders.add(c);
}
ChefOrderAdapter adapter = new ChefOrderAdapter(listOrders, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ChefScreen.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", "0");
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
}
This is the layout for the chef screen:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChefScreen">
<ListView
android:id="#+id/list_chef_orders"
android:layout_width="330dp"
android:layout_height="430dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="15dp"
android:layout_marginTop="81dp"
tools:layout_editor_absoluteX="20dp"
tools:layout_editor_absoluteY="77dp" />
</RelativeLayout>
The adapter:
public class ChefOrderAdapter extends ArrayAdapter<ChefOrderList> {
private List<ChefOrderList> chefOrderList1;
private Context context;
public ChefOrderAdapter(List<ChefOrderList> M, Context C){
super(C, R.layout.listcheforders, M);
this.chefOrderList1 = 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.listcheforders,null,true);
TextView orderNumber = view.findViewById(R.id.tvOrderNumber);
TextView itemType = view.findViewById(R.id.tvItemType);
TextView itemName = view.findViewById(R.id.tvItemName);
TextView orderQuantity = view.findViewById(R.id.tvItemQty);
TextView orderTime = view.findViewById(R.id.tvDateTime);
ChefOrderList chefOrderList = chefOrderList1.get(position);
itemName.setText(chefOrderList.getName());
orderQuantity.setText("Qty: " +chefOrderList.getQty());
if(position>0){
ChefOrderList prevChefOrderList = chefOrderList1.get(position-1);
if(chefOrderList.getOrder() != (prevChefOrderList.getOrder())){
orderNumber.setText("Order: " +chefOrderList.getOrder());
orderTime.setText(chefOrderList.getDate());
}
if(!chefOrderList.getType().equals(prevChefOrderList.getType())){
itemType.setText(chefOrderList.getType());
}
} else {
itemType.setText(chefOrderList.getType());
orderNumber.setText("Order: " +chefOrderList.getOrder());
orderTime.setText(chefOrderList.getDate());
}
return view;
}
}
The model class:
public ChefOrderList(String name, String type, String date, int qty, int order) {
Name = name;
Type = type;
Date = date;
Qty = qty;
Order = order;
}
public String getDate() {
return Date;
}
public String getName() {
return Name;
}
public String getType() {
return Type;
}
public int getQty() {
return Qty;
}
public int getOrder() {
return Order;
}
}
and finally the layout file for the list or orders:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="#+id/tvOrderNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/tvItemName"
android:layout_marginTop="59dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#000"
android:textSize="30sp" />
<TextView
android:id="#+id/tvDateTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/tvItemName"
android:layout_marginTop="15dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#000" />
<TextView
android:id="#+id/tvItemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="166dp"
android:text="placeholderName"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#000" />
<TextView
android:id="#+id/tvItemQty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/tvItemName"
android:layout_marginTop="216dp"
android:text="qty"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#000" />
<TextView
android:id="#+id/tvItemType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/tvItemName"
android:layout_alignStart="#+id/tvItemName"
android:layout_marginBottom="-166dp"
android:paddingBottom="20dp"
android:text=""
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#000"
android:textSize="26sp"
android:textStyle="italic"
tools:text="text" />
</RelativeLayout>
Please check following screenshot, I want to update imageview from parent recyclerview when user click on imageview from nested recyclerview.
I have taken two individual adapters for for parent & nested recyclerview.I am not able to do the functionality for updating image, kindly help.
Parent Recyclerview Adapter:
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {
private ArrayList<PLDModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<PLDModel> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card_view, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String itemTitle = dataList.get(i).getTitle();
final String itemDescription = dataList.get(i).getDescription();
ArrayList<SmallImages> singleSectionItems = dataList.get(i).getSmallImages();
itemRowHolder.itemTitle.setText(Html.fromHtml("<b>" + itemTitle + " </b> " + itemDescription));
SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, singleSectionItems);
itemRowHolder.recyclerSmallImageList.setHasFixedSize(true);
itemRowHolder.recyclerSmallImageList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.recyclerSmallImageList.setAdapter(itemListDataAdapter);
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle, expandImage;
protected ImageView bookmarkImage,largeImage;
protected RecyclerView recyclerSmallImageList;
protected Button btnMore;
public ItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView) view.findViewById(R.id.title);
this.bookmarkImage = (ImageView) view.findViewById(R.id.bookmark);
this.largeImage = (ImageView) view.findViewById(R.id.large_image);
this.expandImage = (TextView) view.findViewById(R.id.expand);
this.recyclerSmallImageList = (RecyclerView) view.findViewById(R.id.recycler_small_image_list);
}
}
}
Nested Recyclerview Adapter:
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SmallImages> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, ArrayList<SmallImages> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.small_images_view, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SmallImages singleItem = itemsList.get(i);
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
//this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.item_small_image);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Using two Recyclerview will be hard to control rather than use a Single adapter and control everything from there.I have just worked on this type of thing that's why I am posting my code there may be some unwanted code which u may need.
/////Adapter class
public class AdapterTodayTrip extends RecyclerView.Adapter<AdapterTodayTrip.VHItem> {
private Context mContext;
private int rowLayout;
private List<ModelRouteDetailsUp> dataMembers;
private ArrayList<ModelRouteDetailsUp> arraylist;
private ArrayList<ModelKidDetailsUp> arraylist_kids;
List<String> wordList = new ArrayList<>();
Random rnd = new Random();
int randomNumberFromArray;
private ModelRouteDetailsUp personaldata;
private ProgressDialog pDialog;
private ConnectionDetector cd;
String img_baseurl = "";
String item = "";
public AdapterTodayTrip(Context mcontext, int rowLayout, List<ModelRouteDetailsUp> tripList, String flag, String img_baseurl) {
this.mContext = mcontext;
this.rowLayout = rowLayout;
this.dataMembers = tripList;
wordList.clear();
this.img_baseurl = img_baseurl;
arraylist = new ArrayList<>();
arraylist_kids = new ArrayList<>();
arraylist.addAll(dataMembers);
cd = new ConnectionDetector(mcontext);
pDialog = KPUtils.initializeProgressDialog(mcontext);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public AdapterTodayTrip.VHItem onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
return new AdapterTodayTrip.VHItem(v);
}
#Override
public int getItemCount() {
return dataMembers.size();
}
#Override
public void onBindViewHolder(final AdapterTodayTrip.VHItem viewHolder, final int position) {
viewHolder.setIsRecyclable(false);
try {
personaldata = dataMembers.get(position);
if (!KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().isEmpty() && !KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().equals("null")) {
viewHolder.tv_trip_id.setText("#" + KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id());
}
****///////inflate the child list here and onclick on the image below in the inflated view it will load the image in the main view****
if (personaldata.getKidlist().size() > 0) {
viewHolder.linear_childview.setVisibility(View.VISIBLE);
viewHolder.tv_total_count.setText(""+personaldata.getKidlist().size());
viewHolder.id_gallery.removeAllViews();
LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
buttonLayoutParams.setMargins(0, 0, 8, 0);
LayoutInflater layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < personaldata.getKidlist().size(); i++) {
View view = layoutInflater.inflate(R.layout.view_child_list, null);
view.setLayoutParams(buttonLayoutParams);
RelativeLayout rl_txt = (RelativeLayout)view.findViewById(R.id.rl_txt);
RelativeLayout rl_img = (RelativeLayout)view.findViewById(R.id.rl_img);
TextView tv_count = (TextView)view.findViewById(R.id.tv_count);
com.app.kidpooldriver.helper.CircularTextView tv_name = (com.app.kidpooldriver.helper.CircularTextView)view.findViewById(R.id.tv_name);
final CircleImageView iv_circular = (CircleImageView)view.findViewById(R.id.iv_circular);
int count = i + 1;
String count1 = "0";
if (count <= 10) {
count1 = "0" + count;
}
tv_count.setText(String.valueOf(count1));
viewHolder.id_gallery.addView(view);
final String baseurl = img_baseurl + "" + personaldata.getKidlist().get(i).getKid_image();
**/////set the url of the small image in the tag here**
if(!baseurl.isEmpty()) {
iv_circular.setTag(baseurl);
}
if (!personaldata.getKidlist().get(i).getKid_image().isEmpty()) {
GradientDrawable bgShape = (GradientDrawable) rl_img.getBackground();
bgShape.setColor(Color.parseColor("#A6b1a7a6"));
rl_txt.setVisibility(View.GONE);
//rl_img.setVisibility(View.VISIBLE);
tv_name.setVisibility(View.GONE);
Log.d("aimg_baseurl", baseurl);
try {
Picasso.with(mContext)
.load(baseurl)
.resize(60,60)
.centerCrop()
.into(iv_circular);
iv_circular.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url=iv_circular.getTag().toString().trim();
if(!url.isEmpty())
KPUtils.showToastShort(mContext,url);
Picasso.with(mContext)
.load(url)
.resize(60,60)
.centerCrop()
.into(viewHolder.img_child);
}
});
} catch (Exception e) {
}
} else {
}
}
}else{
viewHolder.linear_childview.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
class VHItem extends RecyclerView.ViewHolder {
CardView cv_members;
ImageView img_child;
TextView tv_trip_id, tv_trip_status, tv_vehicle_number, tv_trip_start_time, tv_trip_end_time, tv_trip_way, tv_total_count;
LinearLayout id_gallery,linear_childview;
public VHItem(View itemView) {
super(itemView);
img_child= (ImageView) itemView.findViewById(R.id.img_child);
cv_members = (CardView) itemView.findViewById(R.id.cv_members);
tv_trip_id = (TextView) itemView.findViewById(R.id.tv_trip_id);
tv_trip_status = (TextView) itemView.findViewById(R.id.tv_trip_status);
tv_vehicle_number = (TextView) itemView.findViewById(R.id.tv_vehicle_number);
tv_trip_start_time = (TextView) itemView.findViewById(R.id.tv_trip_start_time);
tv_trip_end_time = (TextView) itemView.findViewById(R.id.tv_trip_end_time);
tv_trip_way = (TextView) itemView.findViewById(R.id.tv_trip_way);
tv_total_count = (TextView) itemView.findViewById(R.id.tv_total_count);
id_gallery = (LinearLayout) itemView.findViewById(R.id.id_gallery);
linear_childview= (LinearLayout) itemView.findViewById(R.id.linear_childview);
}
}
}
/////////////////////////// this layout is inflated in every row
view_child_list
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/iv_circular"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/ic_launcher"
app:civ_border_color="#d27959"
app:civ_border_width="1dp" />
<RelativeLayout
android:id="#+id/rl_txt"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="gone">
<com.app.kidpooldriver.helper.CircularTextView
android:id="#+id/tv_name"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="70dp"
android:layout_height="70dp"
android:gravity="center"
android:text="01"
android:textColor="#color/white"
android:textSize="35sp"
tools:ignore="MissingPrefix" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rl_img"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="visible">
<TextView
android:id="#+id/tv_count"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="01"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#ffffff"
android:textStyle="bold"
tools:ignore="MissingPrefix" />
</RelativeLayout>
</FrameLayout>
///// this is the mianlayout which is inflated.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cv_members"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/card_margin"
android:elevation="#dimen/elevation"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:id="#+id/main_body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:layout_marginTop="#dimen/fifteen"
android:orientation="horizontal"
android:paddingLeft="#dimen/ten">
<TextView
android:id="#+id/tv_trip_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#KD09201701"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/twenty"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_trip_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/light_green"
android:gravity="center"
android:padding="5dp"
android:text="In Progress"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/black" />
</LinearLayout>
<TextView
android:id="#+id/tv_vehicle_number"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:text="Route 26U-26D"
android:visibility="gone"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/route_textcolor" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:orientation="horizontal">
<TextView
android:id="#+id/tv_trip_start_time"
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="06:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor" />
<TextView
android:id="#+id/tv_trip_end_time"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="08:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor"
android:visibility="gone" />
</LinearLayout>
<TextView
android:id="#+id/tv_trip_way"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:visibility="gone"
android:paddingRight="20dp"
android:text="Chingrighata > NiccoPark > SDF > College More > DLF 1 > Eco Space"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/grey_textcolor"
android:textStyle="normal" />
<ImageView
android:id="#+id/img_child"
android:layout_width="200dp"
android:layout_gravity="center"
android:layout_height="200dp" />
<LinearLayout
android:id="#+id/linear_childview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/fifteen"
android:orientation="horizontal">
<HorizontalScrollView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:scrollbars="none">
<LinearLayout
android:id="#+id/id_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</HorizontalScrollView>
<LinearLayout
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/ly_ring_circular"
android:gravity="center_vertical">
<TextView
android:id="#+id/tv_total_count"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:ignore="MissingPrefix"
fontPath="fonts/Poppins-Bold.ttf"
android:text="+20"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/white"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
/////POJO CLASS &json parsing & Adapter /////
public class ModelRouteDetailsUp {
String city_id;
String area_name;
String area_status;
String is_active;
String areas;
private ArrayList<ModelKidDetailsUp> kidlist;
///////this is the kid list
public ArrayList<ModelKidDetailsUp> getKidlist() {
return kidlist;
}
public void setKidlist(ArrayList<ModelKidDetailsUp> kidlist) {
this.kidlist = kidlist;
}
}
**///json parsing.......**
public boolean addRideDetails(JSONObject jsonObject) {
Boolean flag = false;
String isstatus = "";
if (jsonObject != null && jsonObject.length() > 0) {
try {
JSONArray mainArray = jsonObject.getJSONArray("schedules");
for (int i = 0; i < mainArray.length(); i++) {
ModelRouteDetailsUp modelRouteDetails = new ModelRouteDetailsUp();
JSONObject c = mainArray.getJSONObject(i);
////// For Route Details //////
JSONObject route_details = c.getJSONObject("route_details");
modelRouteDetails.setDs_id(route_details.optString("ds_id"));
modelRouteDetails.setDriver_id(route_details.optString("driver_id"));
modelRouteDetails.setTrip_id(route_details.optString("trip_id"));
modelRouteDetails.setRoute_id(route_details.optString("route_id"));
modelRouteDetails.setVehicle_id(route_details.optString("vehicle_id"));
modelRouteDetails.setStart_time(route_details.optString("start_time"));
modelRouteDetails.setEnd_time(route_details.optString("end_time"));
////// For Allotted Kids //////
JSONArray kidArray = c.getJSONArray("alloted_kids");
ArrayList<ModelKidDetailsUp> genre = new ArrayList<ModelKidDetailsUp>();
if (kidArray.length() > 0) {
for (int j = 0; j < kidArray.length(); j++) {
ModelKidDetailsUp kidDetailsUp = new ModelKidDetailsUp();
JSONObject kidObject = kidArray.getJSONObject(j);
kidDetailsUp.setKid_name(kidObject.getString("kid_name"));
kidDetailsUp.setKid_gender(kidObject.getString("kid_gender"));
kidDetailsUp.setKid_dob(kidObject.getString("kid_dob"));
kidDetailsUp.setKid_image(kidObject.getString("kid_image"));
genre.add(kidDetailsUp);
}
}
///////add the kidlist here
modelRouteDetails.setKidlist(genre);
////main array contains all the data i.e route details and kidlist for every row
KPHashmapUtils.m_ride_route_details_up.add(modelRouteDetails);
//}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
**/////adapter callfrom class**
private void showData() {
if (KPHashmapUtils.m_ride_route_details_up.size() > 0){
adapterTodayTrip = new AdapterTodayTrip(mContext, R.layout.list_item_todaytrip, KPHashmapUtils.m_ride_route_details_up, "TodayTrip",img_baseurl);
rv_trip_list.setAdapter(adapterTodayTrip);
}else {
tv_msg.setVisibility(View.VISIBLE);
}
}
Generally, the solution is to pass custom interface listener into the nested adapter and than the nested adapter will report any time one of his item clicked.
1.
You can create interface like:
public interface INestedClicked {
onNestedItemClicked(Drawable drawble)
}
2.
Pass in the constructor of SectionListDataAdapter a INestedClicked:
SectionListDataAdapter itemListDataAdapter = newSectionListDataAdapter(mContext, singleSectionItems, new INestedClicked() {
#Override
void onNestedItemClicked(Drawable drawble) {
// Do whatever you need after the click, you get the drawable here
}
});
In the constructor of SectionListDataAdapter save the instance of the listener as adapter parameter
private INestedClicked listener;
4.
When nested item clicked report the listener:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onNestedItemClicked(imageView.getDrawable());
}
}
I have a recyclerview that contains the cardview.The data is coming from server and is populated in a list. The Cardview adapter is not inflating the 2nd value from the list. The activity shows only one value on the screen:
This is the cardview screen
Following is the code for Recycler view layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:scrollbars="vertical"
tools:context="com.appshaala.vorkal.app.ViewWorkerList">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Following is the code for worker_card layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:padding="16dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/WorkerCV"
app:cardBackgroundColor="#color/colorPrimaryDark"
android:elevation="5dp"
card_view:cardCornerRadius="#dimen/card_album_radius">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dp"
>
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip" >
<ImageView
android:id="#+id/pic"
android:layout_width="96dp"
android:layout_height="96dp"
android:src="#drawable/cover"
android:contentDescription="Worker pic" />
</LinearLayout>
<TextView
android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Raja"
android:textSize="35sp"
android:foregroundGravity="center"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/Wrating"
android:layout_alignStart="#+id/Wrating"
android:textAlignment="center" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View Profile"
android:id="#+id/button2"
android:layout_below="#+id/thumbnail"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/Wrating"
android:layout_toStartOf="#+id/Wrating" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call"
android:id="#+id/button3"
android:layout_alignTop="#+id/button2"
android:layout_alignRight="#+id/Wrating"
android:layout_alignEnd="#+id/Wrating" />
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Wrating"
style="?android:attr/ratingBarStyleIndicator"
android:foregroundGravity="center"
android:layout_below="#+id/Name"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:rating="3.5"
android:numStars="5" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Following is the code for worker adapter:
public class WorkerAdapter extends RecyclerView.Adapter<WorkerAdapter.PersonViewHolder> {
private List<Worker> persons;
public static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView personName;
RatingBar personRating;
PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.WorkerCV);
personName = (TextView) itemView.findViewById(R.id.Name);
personRating = (RatingBar) itemView.findViewById(R.id.Wrating);
}
}
public WorkerAdapter(List<Worker> persons)
{
this.persons = persons;
Log.d("Size",""+persons.size());
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.worker_card, parent, false);
PersonViewHolder pvh = new PersonViewHolder(v);
Log.d("here","ya");
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
Log.d("Pos",""+position);
holder.personName.setText(persons.get(position).getName());
holder.personRating.setRating(persons.get(position).getRating());
}
#Override
public int getItemCount() {
if (persons != null) {
return persons.size();
}
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
Following is the code for ViewWorkerList that calls worker adapter and inflates the recycler view:
public class ViewWorkerList extends AppCompatActivity {
//Creating a List of workers
private List<Worker> listWorkers;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private WorkerAdapter adapter;
// Json nodes
private static String KEY_SUCCESS = "success";
private static String KEY_NAME = "name";
private static String KEY_PHONE = "phoneno";
String url = "http://vorkal.com/read_data.php";
ArrayList<HashMap<String, String>> Item_List;
public static final String KEY_SERVICE = "service";
private String service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(),"2nd page",Toast.LENGTH_LONG);
Log.d("2pg","2page");
Intent intent = getIntent();
service = intent.getStringExtra("service"); //if it's a string you stored.
setContentView(R.layout.worker_list_main);
//Initializing our workers list
listWorkers = new ArrayList<>();
Map<String,String> params = new HashMap<String, String>();
params.put("tag", "get_list");
params.put("service", service);
StringRequest stringRequest = new StringRequest (Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.d("response",response.toString());
JSONObject jsonObject=new JSONObject(response);
int success = jsonObject.getInt("success");
//int success=response.getInt(KEY_SUCCESS);
// Log.d("response", response.getString("workers"));
Log.d("sucess",""+success);
String workerArray=jsonObject.getString("workers");
JSONArray jar=new JSONArray(workerArray);
JSONObject json = jar.getJSONObject(0);
Log.d("name",json.getString("name"));
parseData(jar);
} catch (Exception e) {
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//recyclerView.setAdapter(new CardAdapter(listWorkers, this));
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
//Finally initializing our adapter
Log.d("listworkers",listWorkers.get(1).getName());
adapter = new WorkerAdapter(listWorkers);
recyclerView.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("tag", "get_list");
params.put("service", service);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
Worker worker = new Worker();
JSONObject json = null;
try {
json = array.getJSONObject(i);
worker.setImageUrl(json.getString("pic"));
worker.setName(json.getString("name"));
worker.setLocation(json.getString("location"));
worker.setRating(json.getInt("rating"));
worker.setId(json.getInt("id"));
worker.setPhone(json.getInt("phonenumber"));
worker.setOccupation(json.getString("occupation"));
worker.setPrice(json.getInt("price"));
worker.setReview(json.getString("Review"));
} catch (JSONException e) {
e.printStackTrace();
}
listWorkers.add(worker);
}
}
}
The listWorkers contains 2 workers. But only one is getting populated in the cardview. The worker is the normal bean class. I am not able to see the 2nd worker card on the screen. Please help me out and suggest the changes.
I have connected my android application to Firebase and I am sending messages with attributes 'name' and 'status'. status being either sent or received.
I am facing issue while aligning the chat bubble left/right depending upon the status.
Here is the code snippet
message_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/singleMessageContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/message_bubble_received">
<TextView
android:id="#+id/username_text_view"
android:layout_width="wrap_content"
android:paddingLeft="10dip"
android:layout_margin="5dip"
android:text="Hello bubbles!"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/message_text_view"
android:layout_width="wrap_content"
android:paddingLeft="1dip"
android:layout_margin="5dip"
android:text="Hello bubbles!"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ECECEC">
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:divider="#null"
android:layout_marginTop="10dp"
android:listSelector="#android:color/transparent"
android:transcriptMode="alwaysScroll"
android:layout_marginBottom="80dp"/>
<RelativeLayout
android:id="#+id/form"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<EditText
android:id="#+id/message_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="left"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:layout_weight="3"
android:autoText="true"
android:background="#drawable/note_backgroud"
android:hint="Write your question here"
android:minLines="1"
android:paddingLeft="20dp"
android:paddingRight="8dp"
android:paddingBottom="16dp"
android:paddingTop="8dp"/>
<ImageButton
android:id="#+id/cameraButton"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#null"
android:src="#drawable/camera"
android:gravity="top|right"
android:layout_marginRight="8dp"
android:layout_marginLeft="-52dp"
/>
<ImageButton
android:id="#+id/chatSendButton"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/sent"
android:background="#null"
android:layout_gravity="center"
android:layout_marginRight="8dp"
android:layout_marginLeft="8dp"
android:text="Send"
android:onClick="onSendButtonClick"
android:textColor="#ffffff" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
Following is the code snipet for the MessageAdapter
MessageAdapter.java
public abstract class MessageAdapter<T> extends BaseAdapter {
private Query mRef;
private Class<T> mModelClass;
private int mLayout;
private LayoutInflater mInflater;
private List<T> mModels;
private List<String> mKeys;
private ChildEventListener mListener;
private Context context;
private LinearLayout message_row;
private ProgressDialog mProgressDialog;
public MessageAdapter(Query mRef, Class<T> mModelClass, int mLayout, Activity activity) {
this.mRef = mRef;
this.mModelClass = mModelClass;
this.mLayout = mLayout;
this.context = activity.getApplicationContext();
mInflater = activity.getLayoutInflater();
mModels = new ArrayList<T>();
mKeys = new ArrayList<String>();
mProgressDialog = new ProgressDialog(activity);
mProgressDialog.show();
// Look for all child events. We will then map them to our own internal ArrayList, which backs ListView
mListener = this.mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
T model = dataSnapshot.getValue(MessageAdapter.this.mModelClass);
String key = dataSnapshot.getKey();
// Insert into the correct location, based on previousChildName
if (previousChildName == null) {
mModels.add(0, model);
mKeys.add(0, key);
} else {
int previousIndex = mKeys.indexOf(previousChildName);
int nextIndex = previousIndex + 1;
if (nextIndex == mModels.size()) {
mModels.add(model);
mKeys.add(key);
} else {
mModels.add(nextIndex, model);
mKeys.add(nextIndex, key);
}
}
notifyDataSetChanged();
mProgressDialog.dismiss();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// One of the mModels changed. Replace it in our list and name mapping
String key = dataSnapshot.getKey();
T newModel = dataSnapshot.getValue(MessageAdapter.this.mModelClass);
int index = mKeys.indexOf(key);
mModels.set(index, newModel);
notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// A model was removed from the list. Remove it from our list and the name mapping
String key = dataSnapshot.getKey();
int index = mKeys.indexOf(key);
mKeys.remove(index);
mModels.remove(index);
notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
// A model changed position in the list. Update our list accordingly
String key = dataSnapshot.getKey();
T newModel = dataSnapshot.getValue(MessageAdapter.this.mModelClass);
int index = mKeys.indexOf(key);
mModels.remove(index);
mKeys.remove(index);
if (previousChildName == null) {
mModels.add(0, newModel);
mKeys.add(0, key);
} else {
int previousIndex = mKeys.indexOf(previousChildName);
int nextIndex = previousIndex + 1;
if (nextIndex == mModels.size()) {
mModels.add(newModel);
mKeys.add(key);
} else {
mModels.add(nextIndex, newModel);
mKeys.add(nextIndex, key);
}
}
notifyDataSetChanged();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("FirebaseListAdapter", "Listen was cancelled, no more updates will occur");
}
});
}
public void cleanup() {
// We're being destroyed, let go of our mListener and forget about all of the mModels
mRef.removeEventListener(mListener);
mModels.clear();
mKeys.clear();
}
#Override
public int getCount() {
return mModels.size();
}
#Override
public Object getItem(int i) {
return mModels.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) {
view = mInflater.inflate(mLayout, viewGroup, false);
message_row = (LinearLayout) view.findViewById(R.id.singleMessageContainer);
}
T model = mModels.get(i);
Message m = (Message) model;
Log.i("status", m.getStatus());
if (m.getStatus().equals("sent")){
message_row.setGravity(Gravity.LEFT);
message_row.setBackgroundResource(R.drawable.message_bubble_received);
}
else {
message_row.setGravity(Gravity.RIGHT);
message_row.setBackgroundResource(R.drawable.message_bubble_sent);
}
// Call out to subclass to marshall this model into the provided view
populateView(view, model);
return view;
}
protected abstract void populateView(View v, T model);
}
I noticed that the getView() is called more times than the count in the list (eg : if I have 2 messages getview() is called 4 to 5 times).
With the current code chat bubbles are always to the left irrespective of the chat status.
Firebase Data
I recommend to use two layouts - for your bubbles and your opponent. Use them in getView() method of your adapter. For list_item_message_own.xml use right allignment and for list_item_message_opponent.xml use left allignment, it depends on message status.
#Override
public View getView(Context context, Cursor cursor, ViewGroup parent) {
View view;
ViewHolder viewHolder = new ViewHolder();
MessageCache messageCache = ChatManager.getMessageCacheFromCursor(cursor);
boolean ownMessage = isOwnMessage(messageCache.getSenderId());
if (messageCache.getMessagesNotificationType() == null) {
if (ownMessage) {
view = layoutInflater.inflate(R.layout.list_item_message_own, null, true);
} else {
view = layoutInflater.inflate(R.layout.list_item_message_opponent, null, true);
}
viewHolder.timeAttachMessageTextView = (TextView) view.findViewById(R.id.time_attach_message_textview);
viewHolder.verticalProgressBar.setProgressDrawable(context.getResources().getDrawable(R.drawable.vertical_progressbar));
viewHolder.centeredProgressBar = (ProgressBar) view.findViewById(R.id.centered_progressbar);
} else {
view = layoutInflater.inflate(R.layout.list_item_notification_message, null, true);
viewHolder.messageTextView = (EmojiTextView) view.findViewById(R.id.message_textview);
viewHolder.timeTextMessageTextView = (TextView) view.findViewById(
R.id.time_text_message_textview);
}
view.setTag(viewHolder);
return view;
}