I am having a list of items populating through recyclerview with android databinding technique and now I want to pass and populate the same data in detail Activity not getting the right thing to do such. So, kindly help to do this.
public class Fragment extends Fragment {
private FirebaseRecyclerAdapter adapter;
private Firebase mFirebaseRef = new Firebase("https://xyz.firebaseio.com/category/").child("list");
public Fragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.recycler_view, container, false);
final RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
adapter = new FirebaseRecyclerAdapter<List, ViewHolder>List.class, R.layout.fragment,
ViewHolder.class, mFirebaseRef) {
#Override
protected void populateViewHolder(ViewHolder viewHolder, List list, int i) {
FragmentBinding binding = viewHolder.getBinding();
binding.setList(list);
}
};
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), null));
return rootView;
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public FragmentBinding binding;
public ViewHolder(View itemView) {
super(itemView);
binding = DataBindingUtil.bind(itemView);
itemView.setOnClickListener(this);
}
public FragmentBinding getBinding() {
return binding;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailedActivity.class);
**// need help here**
v.getContext().startActivity(intent);
}
}
#BindingAdapter("quantity")
public static void setQuantityText(TextView view, int quantity) {
view.setText(String.valueOf(quantity));
}
public static class Handlers {
public static void increment(View view, int max) {
FragmentBinding binding = DataBindingUtil.findBinding(view);
binding.setQuantity(Math.max(max, binding.getQuantity() + 1));
}
public static void decrement(View view, int min) {
FragmentBinding binding = DataBindingUtil.findBinding(view);
binding.setQuantity(Math.min(min, binding.getQuantity() - 1));
}
}
}
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="List"
type="com.xyz.www.android.model.List"/>
<variable
name="quantity"
type="int"/>
<variable
name="Handlers"
type="com.xyz.www.android.ui.fragments.Fragment.Handlers"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="#dimen/activity_horizontal_margin"
android:paddingEnd="#dimen/activity_horizontal_margin"
android:paddingTop="8dp">
<ImageView
android:layout_width="76dp"
android:layout_height="76dp"
android:contentDescription="#string/content_description"
app:imageUrl="#{List.productImageUrl}"
android:padding="8dp"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginTop="8dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="72dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{List.productTitle}"
android:textSize="16sp"
android:textColor="#android:color/primary_text_light"
app:font="#{`Roboto-Regular.ttf`}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{List.productSku}"
android:textSize="13sp"
android:paddingTop="8dp"
app:font="#{`Roboto-Regular.ttf`}"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Rs"
android:textSize="14sp"
android:paddingTop="8dp"
android:paddingEnd="2dp"
android:paddingStart="2dp"
app:font="#{`Roboto-Regular.ttf`}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{List.productSellingPrice}"
android:textSize="14sp"
android:paddingTop="8dp"
android:paddingStart="2dp"
android:paddingEnd="2dp"
android:textColor="#android:color/primary_text_light"
app:font="#{`Roboto-Regular.ttf`}"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentEnd="true"
android:paddingTop="16dp"
android:paddingBottom="16dp">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/decrease" />
<TextView
android:layout_width="32dp"
android:layout_height="wrap_content"
app:font="#{`Roboto-Regular.ttf`}"
app:quantity="#{quantity}"
android:textAlignment="center" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/increase" />
</LinearLayout>
</RelativeLayout>
#JsonIgnoreProperties(ignoreUnknown=true)
public class List extends BaseObservable {
String productTitle;
String productSku;
String productImageUrl;
String productDescription;
String productMrp;
String productSellingPrice;
public List() {
}
public List(String productTitle, String productSku,
String productImageUrl, String productDescription,
String productMrp, String productSellingPrice) {
this.productTitle = productTitle;
this.productSku = productSku;
this.productImageUrl = productImageUrl;
this.productDescription = productDescription;
this.productMrp = productMrp;
this.productSellingPrice = productSellingPrice;
}
#Bindable
public String getProductTitle() {
return productTitle;
}
#Bindable
public String getProductSku() {
return productSku;
}
#Bindable
public String getProductImageUrl() {
return productImageUrl;
}
#Bindable
public String getProductDescription() {
return productDescription;
}
#Bindable
public String getProductMrp() {
return productMrp;
}
#Bindable
public String getProductSellingPrice() {
return productSellingPrice;
}
There are a few ways to do this. One is to make List Parcelable so that you can pass it as an Intent extra. You'll then be able to extract it and populate the Detail page.
public static final LIST = "ListContent";
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailedActivity.class);
FragmentBinding binding = DataBindingUtil.findBinding(v);
intent.putExtra(LIST, binding.getList());
v.getContext().startActivity(intent);
}
Another is to pass only the ID for the List and read the information again in the detail binding. Add the ID to the List and then you'll be able to extract it when you start the activity:
public static final LIST_ID = "ListID";
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailedActivity.class);
FragmentBinding binding = DataBindingUtil.findBinding(v);
intent.putExtra(LIST_ID, binding.getList().getId());
v.getContext().startActivity(intent);
}
Either way, you can pull the data from the intent in the onCreate of your details Activity:
public void onCreate(...) {
Intent intent = getIntent();
// Using ID:
int id = intent.getIntExtra(LIST_ID);
List list = loadListFromId(id);
// Using Parcelable:
List list = intent.getParcelableExtra(LIST);
//...
}
Related
I have the following classes:
CategoryFragment.java
public class CategoryFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "category_name";
// TODO: Rename and change types of parameters
private int mParam1;
public CategoryFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #return A new instance of fragment CategoryFragment.
*/
// TODO: Rename and change types and number of parameters
public static CategoryFragment newInstance(int param1) {
CategoryFragment fragment = new CategoryFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getInt(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getActivity();
View view = inflater.inflate(R.layout.listado_noticias, container, false);
RecyclerView rw_noticias = view.findViewById(R.id.rw_noticias);
new LoadArticlesTask().execute(MainScreen.mPrefs,MainScreen.hasRemember,view,context,rw_noticias);
return null;
}
}
listado_noticias.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/constraintLayout"
xmlns:tools="http://schemas.android.com/tools">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rw_noticias"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
LoadArticlesTask.java
public class LoadArticlesTask extends AsyncTask<Object, Void, List<Article>> {
private static final String TAG = "LoadArticlesTask";
private View view;
private Context context;
private RecyclerView rw_noticias;
#Override
protected List<Article> doInBackground(Object... params) {
SharedPreferences sp = (SharedPreferences)params[0];
boolean hasRemember = (boolean)params[1];
view = (View)params[2];
context = (Context)params[3];
rw_noticias = (RecyclerView)params[4];
List<Article> res = null;
Properties ini = new Properties();
ini.setProperty(RESTConnection.ATTR_SERVICE_URL,Constants.URL_SERVICE);
ini.setProperty(RESTConnection.ATTR_REQUIRE_SELF_CERT,Constants.CERT_VALUE);
ModelManager.configureConnection(ini);
String strIdUser;
String strApiKey;
String strIdAuthUser;
if(hasRemember){
strIdUser = sp.getString("pref_apikey","");
strApiKey = sp.getString("pref_IdUser","");
strIdAuthUser = sp.getString("pref_strIdAuthUser","");
}else {
strIdUser = ModelManager.getLoggedIdUSer();
strApiKey = ModelManager.getLoggedApiKey();
strIdAuthUser = ModelManager.getLoggedAuthType();
}
//ModelManager uses singleton pattern, connecting once per app execution in enough
if (!ModelManager.isConnected()){
// if it is the first login
if (strIdUser==null || strIdUser.equals("")) {
try {
ModelManager.login(Constants.USER, Constants.PASS);
} catch (AuthenticationError e) {
Log.e(TAG, e.getMessage());
}
}
// if we have saved user credentials from previous connections
else{
ModelManager.stayloggedin(strIdUser,strApiKey,strIdAuthUser);
}
}
//If connection has been successful
if (ModelManager.isConnected()) {
try {
// obtain 6 articles from offset 0
res = ModelManager.getArticles(6, 0);
for (Article article : res) {
// We print articles in Log
Log.i(TAG, String.valueOf(article));
}
} catch (ServerCommunicationError e) {
Log.e(TAG,e.getMessage());
}
}
return res;
}
#Override
protected void onPostExecute(List<Article> articles) {
super.onPostExecute(articles);
Log.i("Articles", articles.toString());
for (Article article : articles) {
// We print articles in Log
Log.i("Articles", String.valueOf(article));
}
refreshList(articles,view);
}
public void refreshList(List<Article> data, View view){
if (data == null){
return;
}
for (Article article : data) {
// We print articles in Log
Log.i("Articles_rl", String.valueOf(article));
}
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rw_noticias.setLayoutManager(layoutManager);
ArticlesAdapter articlesAdapter = new ArticlesAdapter(data);
rw_noticias.setAdapter(articlesAdapter);
((ArticlesAdapter)rw_noticias.getAdapter()).updateData(data);
}
}
ArticlesAdapter.java
public class ArticlesAdapter extends RecyclerView.Adapter<ArticlesAdapter.ArticleViewHolder>{
private List<Article> articulos;
public ArticlesAdapter(List<Article> articulos){
this.articulos = articulos;
}
#NonNull
#Override
public ArticleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout_article, parent, false);
return new ArticleViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ArticleViewHolder holder, int position) {
Bitmap imagen = null;
holder.category.setText(articulos.get(position).getCategory());
holder.title.setText(articulos.get(position).getTitleText());
holder.resumen.setText(articulos.get(position).getAbstractText());
try {
imagen = SerializationUtils.base64StringToImg(articulos.get(position).getImage().getImage());
} catch (ServerCommunicationError serverCommunicationError) {
serverCommunicationError.printStackTrace();
}
holder.thumbnail.setImageBitmap(imagen);
}
#Override
public int getItemCount() {
return articulos.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public void updateData(List<Article>data){
articulos.clear();
articulos.addAll(data);
notifyDataSetChanged(); //notify to repaint the list
}
public void articlesFilterCategory(String category){
for (Article a : articulos){
if(!category.equals("ALL") && !a.getCategory().equals(category)){
articulos.remove(a);
}
}
}
public static class ArticleViewHolder extends RecyclerView.ViewHolder{
CardView cv;
TextView category;
TextView title;
TextView resumen;
ImageView thumbnail;
public ArticleViewHolder(#NonNull View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.card_article);
category = (TextView)itemView.findViewById(R.id.category_noticia);
resumen = (TextView)itemView.findViewById(R.id.resumen_noticia);
thumbnail = (ImageView)itemView.findViewById(R.id.thumbnail);
}
}
}
card_layout_article.xml
<androidx.cardview.widget.CardView 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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:foreground="?attr/selectableItemBackground"
android:ellipsize="end"
android:id="#+id/card_article"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16dp"
android:paddingHorizontal="1dp">
<ImageView
android:id="#+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="231dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="1dp"
android:layout_marginTop="1dp"
android:adjustViewBounds="true"
android:background="#drawable/a15877171854035"
android:cropToPadding="true"
android:scaleType="fitXY"
android:src="#drawable/degradado" />
<View
android:layout_width="match_parent"
android:layout_height="233dp"
android:background="#drawable/degradado" />
<TextView
android:id="#+id/title_noticia"
android:layout_width="193dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/thumbnail"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="107dp"
android:layout_marginEnd="107dp"
android:layout_marginBottom="95dp"
android:text="Nuevo caso de coronavirus"
android:textAlignment="center"
android:textColor="#color/cardview_light_background"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/category_noticia"
android:layout_width="91dp"
android:layout_height="31dp"
android:layout_alignBottom="#+id/thumbnail"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="11dp"
android:layout_marginEnd="316dp"
android:layout_marginBottom="145dp"
android:text="NATIONAL"
android:textAlignment="center"
android:textColor="#color/cardview_light_background"
android:textSize="15dp"
android:textStyle="bold" />
<TextView
android:id="#+id/resumen_noticia"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_alignBottom="#+id/thumbnail"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:layout_marginBottom="-1dp"
android:text="Nuevo caso de coronavirus"
android:textAlignment="viewStart"
android:textColor="#color/cardview_light_background"
android:textSize="11dp"
android:textStyle="bold" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
In the log.i that I have in the Post Execute of the async task I can see how the articles are formed (The Article class has a toString () function).
But I can't get the articles to be seen in the RecyclerView. What am I doing wrong?
Capture: Main screen with recyclerView empty...
Thanks!
Pass the instance of RecyclerView like -
new LoadArticlesTask().execute(MainScreen.mPrefs, MainScreen.hasRemember, view, rw_noticias, context);
Receive this on LoadArticlesTask as you are doing with View.
Don't re-initialize/use this code inside your class -
RecyclerView rw_noticias = view.findViewById(R.id.rw_noticias);
In your card_layout_article.xml, make height wrap_content for cardview:
<androidx.cardview.widget.CardView 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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
........
........
Also in the layout of your recycler view instead of ConstraintLayout try to use RelativeLayout as the parent:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/constraintLayout"
xmlns:tools="http://schemas.android.com/tools">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rw_noticias"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I am trying to add a button in the end of my recycler view and make that add button appear as a fragment. Previously it worked. But I don't know why it doesn't work at the moment. I've changed it into Frame Layout according to google and some StackOverflow question but it is still not showing up. When I put a toast inside the onClick function, the toast showed up. It's weird. Is it wrong somewhere else?
MessageAdapter.java
#Override
protected void onBindViewHolder(final MessagesHolder holder, int position, Messages model) {
holder.textViewMessages.setText(model.getMessages());
holder.textViewUser.setText(model.getUser());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd yyyy, hh:mm a");
String testtimeStamp = (model.getTimePosted().toDate().toString());
String testtimeStamp2 = simpleDateFormat.format(new Date(testtimeStamp));
holder.timeStamp.setText(testtimeStamp2);
holder.bAdd.setVisibility(View.GONE);
holder.container.setVisibility(View.GONE);
//Compare size and add button at buttom of view
if(position==getItemCount()-1){
holder.bAdd.setVisibility(View.VISIBLE);
}
holder.bAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.container.setVisibility(View.VISIBLE);
AppCompatActivity activity = (AppCompatActivity)v.getContext();
Fragment replyFrag = new AddReplyFragment();
Bundle extras = new Bundle();
extras.putString("USER","Test_User");
replyFrag.setArguments(extras);
replyFrag.setArguments(extrasFromTitle);
activity.getSupportFragmentManager().beginTransaction()
.replace(R.id.replyFragment,replyFrag).commit();
}
});
}
#NonNull
#Override
public MessagesHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewforuminterface,parent,false);
EmojiCompat.init(new BundledEmojiCompatConfig(view.getContext()));
return new MessagesHolder(view);
}
class MessagesHolder extends RecyclerView.ViewHolder{
EmojiTextView textViewMessages;
EmojiTextView textViewUser;
TextView timeStamp;
Button bAdd;
FrameLayout container;
public MessagesHolder(#NonNull View itemView) {
super(itemView);
textViewMessages = itemView.findViewById(R.id.tvDescription_reply);
textViewUser = itemView.findViewById(R.id.tvUsername);
timeStamp = itemView.findViewById(R.id.tvTimestampMessages);
bAdd = itemView.findViewById(R.id.bAdd);
container = itemView.findViewById(R.id.replyFragment);
}
}
AddReplyFragment.java
public class AddReplyFragment extends Fragment {
FirebaseFirestore db = FirebaseFirestore.getInstance();
Button bAddReply;
EditText reply;
Timestamp now = Timestamp.now();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_add_reply_fragment,container,false);
final String username = getArguments().getString("USER");
final String forum_title = getArguments().getString("TITLE");
final String forum_type = getArguments().getString("FORUM_TYPE");
final String forum_id = getArguments().getString("FORUM_ID");
reply = (EditText)view.findViewById(R.id.etReply);
bAddReply = (Button)view.findViewById(R.id.bAddReply);
String userReply = reply.getText().toString();
final Map<String, Object> reply = new HashMap<>();
reply.put("messages",userReply);
reply.put("timePosted",now);
reply.put("user",username);
bAddReply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.collection(forum_type).document(forum_id).collection("messages").add(reply);
}
});
return view;
}
}
cardviewforuminterface.xml
<?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"
android:weightSum="4">
<LinearLayout
android:id="#+id/reply_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:weightSum="4">
<androidx.emoji.widget.EmojiTextView
android:id="#+id/tvDescription_reply"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="description"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/users_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:weightSum="3">
<androidx.emoji.widget.EmojiTextView
android:id="#+id/tvUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="name"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tvTimestampMessages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:text="timestamp"
android:textIsSelectable="false"
android:textSize="15sp" />
</LinearLayout>
<Button
android:id="#+id/bAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Add Reply" />
<FrameLayout
android:id="#+id/replyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
</FrameLayout>
</LinearLayout>
activity_add_reply_fragment.xml
<?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="match_parent"
android:layout_height="150dp"
android:orientation="vertical"
tools:context=".Fragment.AddReplyFragment">
<TextView
android:id="#+id/tvReply"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:padding="10dp"
android:text="Your Reply"
android:textSize="18sp" />
<EditText
android:id="#+id/etReply"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="10"
android:hint="Type your reply here"
android:inputType="textPersonName"
android:padding="10dp" />
<Button
android:id="#+id/bAddReply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="Submit Reply" />
</FrameLayout>
The code I added in my adapter.
holder.container.setId(newContainerId);
final int newContainerId = getUniqueId();
public int getUniqueId(){
return (int) SystemClock.currentThreadTimeMillis();
}
This is my last code
public class MessagesAdapter extends FirestoreRecyclerAdapter<Messages, MessagesAdapter.MessagesHolder> {
FirebaseFirestore db = FirebaseFirestore.getInstance();
MessagesAdapter context;
Bundle extrasFromInterface;
public MessagesAdapter(#NonNull FirestoreRecyclerOptions<Messages> options,Bundle bundle) {
super(options);
extrasFromInterface = bundle;
}
#Override
protected void onBindViewHolder(final MessagesHolder holder, int position, Messages model) {
final int newContainerId = getUniqueId();
holder.textViewMessages.setText(model.getMessages());
holder.textViewUser.setText(model.getUser());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd yyyy, hh:mm a");
String uncovertedTimeStamp = (model.getTimePosted().toDate().toString());
String ConvertedTimeStamp = simpleDateFormat.format(new Date(uncovertedTimeStamp));
holder.timeStamp.setText(ConvertedTimeStamp);
holder.bAdd.setVisibility(View.GONE);
holder.container.setVisibility(View.GONE);
//Compare size and add button at buttom of view
if(position==getItemCount()-1){
holder.bAdd.setVisibility(View.VISIBLE);
}
holder.bAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.container.setId(newContainerId);
holder.container.setVisibility(View.VISIBLE);
AppCompatActivity activity = (AppCompatActivity)v.getContext();
Fragment replyFrag = new AddReplyFragment();
Bundle extras = new Bundle();
extras.putString("USER","Test_User");
replyFrag.setArguments(extras);
replyFrag.setArguments(extrasFromInterface);
activity.getSupportFragmentManager().beginTransaction()
.replace(newContainerId,replyFrag).commit();
}
});
}
public int getUniqueId(){
return (int) SystemClock.currentThreadTimeMillis();
}
#NonNull
#Override
public MessagesHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewforuminterface,parent,false);
EmojiCompat.init(new BundledEmojiCompatConfig(view.getContext()));
context = this;
return new MessagesHolder(view);
}
class MessagesHolder extends RecyclerView.ViewHolder{
EmojiTextView textViewMessages;
EmojiTextView textViewUser;
TextView timeStamp;
Button bAdd;
FrameLayout container;
public MessagesHolder(#NonNull View itemView) {
super(itemView);
textViewMessages = itemView.findViewById(R.id.tvDescription_reply);
textViewUser = itemView.findViewById(R.id.tvUsername);
timeStamp = itemView.findViewById(R.id.tvTimestampMessages);
bAdd = itemView.findViewById(R.id.bAdd);
container = itemView.findViewById(R.id.replyFragment);
}
}
#Override
public int getItemCount() {
return super.getItemCount();
}
}
I want to integrate my chatbot(created by dialogflow) to my apps and I have create the xml files but I didn't find a way how to match between them.
I have already database using room library persistance .And, I'm coding with Java.
How can I itegrate my agent into my apps?And how to add a recylerViewAdapter for my chatmessages.
Thank you
msg_list.xml
<?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="wrap_content">
<TextView
android:id="#+id/leftText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_alignParentStart="true"
android:text="Hello this is me!!"
android:padding="8dp"
android:textColor="#212121"
android:background="#drawable/left_background"
android:elevation="2dp"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/rightText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_alignParentEnd="true"
android:text="Hi!! How are you!!"
android:background="#drawable/right_background"
android:textColor="#fff"
android:padding="8dp"
android:elevation="2dp"
android:layout_alignParentRight="true" />
</RelativeLayout>
Chatbot.xml
<?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=".Chatbot">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:paddingBottom="50dp"
android:clipToPadding="false"
android:background="#f4f6f7"
tools:listitem="#layout/msglist"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="10dp"
android:elevation="2dp"
android:layout_toStartOf="#+id/addBtn"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:layout_toLeftOf="#+id/addBtn">
<EditText
android:id="#+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:background="#fff"
android:hint="Type a Message"
android:minHeight="50dp"
android:textSize="18sp" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/addBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentEnd="true"
android:background="#drawable/back_fab"
android:layout_marginBottom="10dp"
android:layout_marginEnd="5dp"
android:elevation="4dp"
android:layout_centerInParent="true"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp">
<ImageView
android:id="#+id/fab_img"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_centerInParent="true"
android:src="#drawable/ic_send_white_24dp"
android:tint="#fff"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
ChatbotActivity
public class Chatbot extends AppCompatActivity implements AIListener {
RecyclerView recyclerView;
EditText message;
RelativeLayout addBtn;
ChatbotAdapter adapter;
Boolean flagFab = true;
private AIService aiService;
private AIServiceContext customAIServiceContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatbot);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
message = (EditText)findViewById(R.id.message);
addBtn = (RelativeLayout)findViewById(R.id.addBtn);
recyclerView.setHasFixedSize(true);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = message.getText().toString().trim();
if (!message.equals("")) {
ChatMessage chatMessage = new ChatMessage(msg, "user");
}
message.setText("");
}
});
adapter = new ChatbotAdapter();
recyclerView.setAdapter(adapter);
final AIConfiguration config = new AIConfiguration("Acces",
AIConfiguration.SupportedLanguages.French,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, config);
customAIServiceContext = AIServiceContextBuilder.buildFromSessionId("ID");
aiService.setListener(this);
final AIDataService aiDataService = new AIDataService(config);
final AIRequest aiRequest = new AIRequest();
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = message.getText().toString().trim();
if (!msg.equals("")) {
aiRequest.setQuery(msg);
new AsyncTask<AIRequest,Void, AIResponse>(){
#Override
protected AIResponse doInBackground(AIRequest... aiRequests) {
final AIRequest request = aiRequests[0];
try {
final AIResponse response =
aiDataService.request(aiRequest);
return response;
} catch (AIServiceException e) {
}
return null;
}
#Override
protected void onPostExecute(AIResponse response) {
if (response != null) {
Result result = response.getResult();
String reply = result.getFulfillment().getSpeech();
}
}
}.execute(aiRequest);
}
else {
aiService.startListening();
}
message.setText("");
}
});
}
#Override
public void onResult(AIResponse response) {
}
#Override
public void onError(AIError error) {
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
}
#Override
public void onListeningCanceled() {
}
#Override
public void onListeningFinished() {
}
}
Chatmessage
public class ChatMessage {
private String msgText;
private String msgUser;
public ChatMessage(String msgText, String msgUser){
this.msgText = msgText;
this.msgUser = msgUser;
}
public ChatMessage(){
}
//+getter & setter
}
ChatbotAdapter
//I don't know how to code this class
public class ChatbotAdapter extends RecyclerView.Adapter<ChatbotAdapter.ChatHolder>
{
#NonNull
#Override
public ChatHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.msglist, viewGroup, false);
return new ChatHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ChatHolder chatHolder, int i) {
}
#Override
public int getItemCount() {
return 0;
}
public class ChatHolder extends RecyclerView.ViewHolder {
TextView leftText, rightText;
public ChatHolder(View itemView) {
super(itemView);
leftText = (TextView) itemView.findViewById(R.id.leftText);
rightText = (TextView) itemView.findViewById(R.id.rightText);
}
}
}
Your question is not that clear. Please add some more details like what is you want, what you have implemented and what issue is coming.
You may also try my implementation. I am not using Recycler view in my implementation, but you could follow the following article I wrote for integrating Dialogflow with Android. Try an follow the V2 version as V1 will phase out by October this year.
Also, Do not use fragment for Chatbot as it somehow does not work. Try and make a simple chatbot using my implementation and then you can work towards your own implementation.
Hope it works.
I tried the solutions on the other similar posts that I found here but they did not help me. I hope someone can help.
I get data from Unsplash's API and the ArrayList contains 10 items once I get a response, that's why I think It has to be something with the way the view is inflated.
This is code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "unsplash";
private final String CLIENT_ID = "...myclientID...";
// testing keyword used on the API to search for pictures
private final String KEYWORD = "stackOverflow";
private final String urlBase = "https://api.unsplash.com/";
private Retrofit retrofit;
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder()
.baseUrl(urlBase)
.addConverterFactory(GsonConverterFactory.create())
.build();
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerViewAdapter = new RecyclerViewAdapter();
recyclerView.setAdapter(recyclerViewAdapter);
getData();
}
private void getData() {
PictureService service = retrofit.create(PictureService.class);
Call<PictureResponse> pictureResponseCall = service.getPictureList(KEYWORD, CLIENT_ID);
pictureResponseCall.enqueue(new Callback<PictureResponse>() {
#Override
public void onResponse(Call<PictureResponse> call, Response<PictureResponse> response) {
if (response.isSuccessful()){
PictureResponse pictureResponse = response.body();
ArrayList<UnsplashPic> pictureList = pictureResponse.getResults();
recyclerViewAdapter.addPictures(pictureList);
}else{
Log.e (TAG, " onResponse " + response.errorBody());
}
}
#Override
public void onFailure(Call<PictureResponse> call, Throwable t) {
Log.e (TAG, " onFailure " + t.getMessage());
}
});
}
}
My adapter class:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UnsplashPic> pictureList;
public RecyclerViewAdapter (){
pictureList = new ArrayList<>();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_view_holder, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
UnsplashPic pic = pictureList.get(i);
viewHolder.artistName.setText(pic.user.getUsername());
viewHolder.unsplash.setText("Unsplash");
}
#Override
public int getItemCount() {
return pictureList.size();
}
public void addPictures(ArrayList<UnsplashPic> pictureList) {
pictureList.addAll(pictureList);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView artistName;
private TextView unsplash;
public ViewHolder (View itemView){
super(itemView);
imageView = itemView.findViewById(R.id.imageview);
artistName = itemView.findViewById(R.id.artist_name);
unsplash = itemView.findViewById(R.id.unsplash_name);
}
}
}
item_view_holder.xml
<?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">
<ImageView
android:id="#+id/imageview"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="#ababab"
android:contentDescription="unsplash picture" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Photo by "/>
<TextView
android:id="#+id/artist_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="on "/>
<TextView
android:id="#+id/unsplash_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true" />
</LinearLayout>
activity_main.xml
<LinearLayout
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"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Search for pictures"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerview">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Here:
public void addPictures(ArrayList<UnsplashPic> pictureList) {
pictureList.addAll(pictureList);
notifyDataSetChanged();
}
you are actually adding the content of the pictureList you send as parameter of the function to that same list, your list from adapter is not updated.
You should do like this instead:
public void addPictures(ArrayList<UnsplashPic> pictureList) {
this.pictureList.addAll(pictureList);
notifyDataSetChanged();
}
Hi I ma trying to build an app that has a list of events retrieved from a firebase database but when I run it it displays just the first event stored.
there is the code I used to generate the list:
private RecyclerView recyclerView;
private FirebaseRecyclerAdapter<Event,EventViewHolder> firebaseRecyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendario);
recyclerView = (RecyclerView) findViewById(R.id.eventiList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Query query = FirebaseDatabase.getInstance().getReference("Eventi");
FirebaseRecyclerOptions<Event> options =
new FirebaseRecyclerOptions.Builder<Event>().setQuery(query, Event.class).build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Event, EventViewHolder>(options) {
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.event_layout, parent, false);
return new EventViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull EventViewHolder holder, final int position, #NonNull Event model) {
holder.setDay(model.getData().substring(0,2));
holder.setMonth(model.getMese());
holder.setName(model.getNome());
holder.setLuogo(model.getLuogo());
holder.setendStart(model.getOra_inizio()+ " - "+ model.getOra_fine());
holder.mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class EventViewHolder extends RecyclerView.ViewHolder
{
View mview;
public EventViewHolder(View itemView)
{
super(itemView);
mview=itemView;
}
public void setDay(String day)
{
TextView mtext= (TextView)mview.findViewById(R.id.day);
mtext.setText(day);
}
public void setName(String name)
{
TextView maut=(TextView)mview.findViewById(R.id.Event_Name);
maut.setText(name);
}
public void setMonth(String month)
{
TextView maut=(TextView)mview.findViewById(R.id.month);
maut.setText(month);
}
public void setLuogo(String luogo)
{
TextView maut=(TextView)mview.findViewById(R.id.luogo);
maut.setText(luogo);
}
public void setendStart(String endStart)
{
TextView maut=(TextView)mview.findViewById(R.id.start_end);
maut.setText(endStart);
}
}
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
//mAdapter.stopListening();
firebaseRecyclerAdapter.stopListening();
}
this is the code of the model class
public class Event {
private String Nome;
private String data;
private String descrizione;
private String luogo;
private String mese;
private String ora_fine;
private String ora_inizio;
private String type;
public Event()
{
}
public Event(String nome, String data, String descrizione, String luogo, String mese, String ora_fine, String ora_inizio, String type) {
Nome = nome;
this.data = data;
this.descrizione = descrizione;
this.luogo = luogo;
this.mese = mese;
this.ora_fine = ora_fine;
this.ora_inizio = ora_inizio;
this.type = type;
}
public String getNome() {
return Nome;
}
public String getData() {
return data;
}
public String getDescrizione() {
return descrizione;
}
public String getLuogo() {
return luogo;
}
public String getMese() {
return mese;
}
public String getOra_fine() {
return ora_fine;
}
public String getOra_inizio() {
return ora_inizio;
}
public String getType() {
return type;
}
}
this is the Calendar activity layout
<android.support.v4.widget.DrawerLayout 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=".Calendario"
android:id="#+id/Calendar_draw">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/eventiList"></android.support.v7.widget.RecyclerView>
</android.support.v4.widget.DrawerLayout>
This is the code for the recycler view row
<?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">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="119dp"
android:background="#color/darkBlue">
<TextView
android:id="#+id/day"
android:layout_width="86dp"
android:layout_height="66dp"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/Event_Name"
android:layout_marginStart="18dp"
android:textColor="#color/white"
android:textSize="50dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="18dp" />
<TextView
android:id="#+id/month"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignStart="#+id/day"
android:layout_marginBottom="11dp"
android:textColor="#color/white"
android:textStyle="bold"
android:layout_alignLeft="#+id/day" />
<TextView
android:id="#+id/Event_Name"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="124dp"
android:layout_marginTop="13dp"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColor="#color/white"
android:textStyle="bold"
android:layout_alignParentLeft="true"
android:layout_marginLeft="124dp" />
<TextView
android:id="#+id/start_end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginStart="135dp"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/white"
android:textStyle="italic" />
<TextView
android:id="#+id/luogo"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_alignStart="#+id/start_end"
android:layout_below="#+id/day"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/white"
android:textStyle="italic" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
As you can see from the image that follows it displays just one event and I have 5 in the database
Display
The code worked fine for other lists that are in the app I don't understand why it is not working for this one hope I can get an answer here, thanks
Edit: this is the Database tree
Database Tree
Problem Solved, the layout_height parameter was set to match_parent in the event_layout LinearLayout and CardView. I set it to wrap_content on both and it worked.